i'm making a program (w/python 2.7) to approximate sin(x) with taylor series, here's the code:
from math import pi
from math import sin
from math import factorial
x=float(raw_input("Degree(in radian, example: 5*pi/4): "))
n=input("n: ")
Sum=0
for i in range(1,n+1):
Sum=Sum+(pow(-1,(i+1))*pow(x,(2*i-1))/factorial(2*i-1))
error=math.fabs(sin(x)-Sum)
print "Using Taylor series for sin(%s) with n = %d returns %f,with error= %f"(x,n,Sum,error)
(sorry for the from math import mess up there, not exactly good with this)
however, when run with x = 5*pi/4, the program returns
ValueError: invalid literal for float(): 5*pi/4
what am I doing wrong here? I think that python reads x as a string and fails to float that, but what do I know
any help would be appreciated!
float()function doesn't understand'5*pi/4'any more than it understands'airspeed of an unladen swallow plus two'. You have to pass it a floating-point number or its string representation, like'4'or'2.5883'.raw_input()equivalent is calledinput()there andprintis a function. The rest should be mostly the same. That said, you can hardcode the input value to get closer to the required minimal example.