0
import math


def sine_func(x):
    power = 0
    sine = x
    add = (-1)**(power)*(x**(2*power+1))/(math.factorial((2*power+1)))
    while math.fabs(add) > 1.0e-8:
        sine += add        
        power += 1
        add == (-1)**(power)*(x**2*power+1)/(math.factorial((2*power+1)))

return sine

print(sine_func(1))

Program is just running forever, any thoughts on where I made my error?

Brian
  • 151
  • 2
  • 9
  • you should remove the underscore after `add_` in line 8. – hochl Jan 28 '14 at 14:45
  • ... and perhaps that last "`==`" should be something else? ... and sine() vs sine_func()? Sounds like this isn't actually your code.. – Andrew Jaffe Jan 28 '14 at 14:46
  • oops, thanks, i changed some variable names to make for easier readability on the forums, but still produces the same problem though – Brian Jan 28 '14 at 14:46
  • Why would I remove the "==", i want to set add equal to that – Brian Jan 28 '14 at 14:47
  • I couldn't make the code run OOTB ... and add seems to always be one. – hochl Jan 28 '14 at 14:47
  • I made some changes for easier readability because i had to have long ass names for class, i think i fixed all the naming errors though – Brian Jan 28 '14 at 14:48
  • Code runs fine. But the value is maybe wrong. – Stefan Jan 28 '14 at 14:52
  • Actually, repeatedly calculating the power and factorial is not a good idea, it would be better to remember the actual value of them and simply adjust them for each iteration. This will save tons of calculation time. Additionally [see this answer](http://stackoverflow.com/a/345117/589206). – hochl Jan 28 '14 at 15:19
  • Thanks, I'll take a look at that. We have to use power series approximation though – Brian Jan 28 '14 at 15:25
  • Just compared my version to yours and it performs 25% faster, so the speedup is modest. Still a speedup :) [both versions use a Taylor series]. – hochl Jan 28 '14 at 15:48

2 Answers2

3

This line:

add_ == (-1)**(power_int)*(x**2*power_int+1))/(math.factorial((2*power_int+1)))

Neither refers to the previous variable ("add" != "add_") nor assigns any value - == is comparison in Python, not assignment. Try:

add = (-1)**(power_int)*(x**2*power_int+1))/(math.factorial((2*power_int+1)))
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
0

Your code is running fine for me (Python 3.3.3), after fixing the brackets and the initialization as sine=0.

import math

def sine_func(x):
    power = 0
    sine = 0
    add = (-1)**(power)*(x**(2*power+1))/(math.factorial((2*power+1)))
    while math.fabs(add) > 1.0e-8:
        sine += add        
        power += 1
        add = (-1)**(power)*(x**(2*power+1))/(math.factorial((2*power+1)))
return sine
Stefan
  • 2,460
  • 1
  • 17
  • 33