英文:
Taylor series of cosx expansion in Python
问题
我想使用泰勒展开式编写一个cos(x)的函数,但不使用math.factorial函数。我将2i的阶乘定义为:
def factorial_two(i):
if i < 0:
#处理负数
print("错误:无法计算负数的阶乘!")
return None
elif i == 0:
#特殊情况i = 0
return 1
else:
i = i * 2
#一般情况
fact = 1
while i > 0:
fact = fact * i
i = i - 1
return fact
然后我定义cosine的近似值:
def cosine_approx(x, n):
sum = 0
for i in range(0, n+1):
sum += ((-1) ** i) * (x**(2*i)/ factorial_two(i))
return sum
当我对任何x和任何n运行此函数时,结果总是1.0。当我尝试对cosine_approx(x, n)使用相同的函数,但改用基本的math.factorial(2*i)时,我得到了正确的结果。所以问题是,我在定义中哪里出错了?或者我使用它的方式不对?谢谢。
英文:
I want to write a function of cos(x) using the Taylor Expansion, but not using the math.factorial function.
I defined the factorial of 2i as:
def factorial_two(i):
if i < 0:
#Handling negative numbers
print("Error: can't compute the factorial of a negative number!")
return None
elif i == 0:
#The special case i = 0
return 1
else:
i = i * 2
#The general case
fact = 1
while i > 0:
fact = fact * i
i = i - 1
return fact
Then I defined the approximation of cosine as:
def cosine_approx(x,n):
sum = 0
for i in range(0, n+1):
sum += ((-1) ** i) * (x**(2*i)/ factorial_two(i))
return sum
When I run this for any x and any n I always get 1.0 as the result. When I tried the exact same function for cosine_approx(x,n), but instead use the basic math.factorial(2*i) I get the correct results. So the question is, where did I go wrong with by definition? Or am I not using it correctly?
Thank you in advance.
答案1
得分: 1
你的代码出现了错误,你把 return sum
放在了 for 循环中!
所以 sum 会一直是 1.0 并被返回。
你应该将它移到 for 循环之外。
for i in range(0, n+1):
sum += ((-1) ** i) * (x**(2*i) / factorial_two(i))
return sum
像这样。
英文:
your code has an error you put return sum
in the for loop!!
so sum always be 1.0 and returend.
you should put that out of for loop.
for i in range(0, n+1):
sum += ((-1) ** i) * (x**(2*i)/ factorial_two(i))
return sum
like that.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论