algorithm - Java program gives incorrect Taylor series term for function e^x -
//java program asks user input number e^x=1+x+x^2/2! +x^3/3!... e mathematical constant equal 2.718... import java.util.scanner; public class taylor_2 { public static void main(string args[]) { scanner input=new scanner(system.in); double x; //input x double factorial=1; //initializes factorial int counter=1; //initializes counter double result=1; //initializes result system.out.println("enter non negative number"); //asks user enter x x=input.nextint(); //output in while loop continue generated if user doesn't entered negative number while(x<1){ system.out.println("i said entered positive number"); x=input.nextint(); } while(x>counter){ factorial=factorial*counter;//factorial formula result=result+(math.pow(x,counter))/factorial; //equation e^x=1+x+x^2/2! +x^3/3! counter++; } system.out.println("taylor series " +result);//output taylor equation e^x } } here output of code:
enter non negative number
2
taylor series 4.0
when entered 2 , should have outputted 7.3890560983 instead of 4.0 since e=2.718... , e^2=7.3890560983. doing wrong?
the problem taylor series not same function e^x. return function close function e^x.
for understanding better, recommend second picture of next link:
https://en.wikipedia.org/wiki/taylor_series
you can see in previous picture n getting larger function getting more accurate.
your code's problem x value n value, , not true.
x: must value want e^x.
n: accurate of equation. larger means more accurate.
so must change while(x>counter) while(n>counter), n can either variable user selected accuracy, or constant selected accurcy.
i think until x=100, n=150 should work.
i hope helps you! :)
Comments
Post a Comment