Taylor series of cosx expansion in Python 在Python中展开cosx的泰勒级数

huangapple go评论60阅读模式
英文:

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 &lt; 0:
        #Handling negative numbers
        print(&quot;Error: can&#39;t compute the factorial of a negative number!&quot;)
        return None
    elif i == 0:
        #The special case i = 0
        return 1
    else:
        i = i * 2
        #The general case
        fact = 1
        while i &gt; 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.

huangapple
  • 本文由 发表于 2023年2月16日 06:19:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75465957.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定