0

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!

2
  • 2
    Python's 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'. Commented Mar 27, 2016 at 8:22
  • Don't bother learning Python 2, rather switch to Python 3 directly. The raw_input() equivalent is called input() there and print is 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. Commented Mar 27, 2016 at 8:30

3 Answers 3

1

You are right, python does read x as a string:

y = raw_input("Degree(in radian, example: 5*pi/4): ")
print y => 5*pi/4

You would have to precompute the value in radian and pass it to your program:

(5 * math.pi)/2 = 7.853981633974483

This would be the value you give as input to your program.

Sign up to request clarification or add additional context in comments.

Comments

1

There may be a solution for achieving what you want. Read the documentation of the Python 2 input() function before using this solution though. The documentation also explains the reason it was removed in Python 3!

Here's the code:

from math import pi
x = input()
print x

If you run this code and input 3 * pi, it will print 9.42477796076938.

Comments

1

If you want to take values in the a*pi/b format from the command line, you can use the following.

x=(raw_input("Degree(in radian, example: 5*pi/4): "))
numerator =  float (x.split('*')[0])
denominator =float (x.split('/')[1]) 
x = numerator* pi /denominator

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.