正弦函数的幂级数展开

时间:2022-09-25 20:22:31
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))

打印(sine_func(1))

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

程序一直在运行,有什么想法吗?

2 个解决方案

#1


0  

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

在将括号和初始化设置为sin =0之后,您的代码对我来说运行良好(Python 3.3.3)。

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

#2


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”!=“add_”),也不指定任何值- ==是Python中的比较,而不是赋值。试一试:

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

#1


0  

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

在将括号和初始化设置为sin =0之后,您的代码对我来说运行良好(Python 3.3.3)。

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

#2


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”!=“add_”),也不指定任何值- ==是Python中的比较,而不是赋值。试一试:

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