递归逼近正弦

时间:2018-03-28 02:38:37

标签: python recursion series sine

所以我试着写一个由两个递归函数组成的文件。其中一个计算通过泰勒系列近似正弦所需的阶乘。第二个是另一个递归函数,它将sine的值作为一个浮点值输出,并且将达到输入的术语数量。这是我想要获得enter image description here

的数学表示

到目前为止,这是我的代码(由于我在实际正弦计算功能方面遇到困难,因此未完成):

def main():
    ang = int(input("Enter the angle to approximate (in radians): "))
    trms = int(input("Enter the amount of terms to compute: "))
    sinApprox(ang,trms)
def calcFac(x):
    if x <= 0:
        return 1
    else:
        return x * calcFac(x-1)
def sinApprox(angle, terms):
    if calcFac(terms) <= 0:
        return (sinApprox(angle,terms)/calcFac(terms))
    elif terms % 2 == 0:
        return sinApprox(angle**) 

请注意,这两个函数也必须是纯函数和递归函数。

1 个答案:

答案 0 :(得分:0)

这是一种可以做到这一点的方法。

def calcFac(x):
    if x == 1 or x == 0: return 1
    val = 1
    for i in range(2, x+1):
        val = val * i
    return val

def sinApprox(angle, terms):
    mult = 1
    if terms % 2 == 0: mult = -1

    power = 2*terms - 1
    val = angle ** power
    val = mult * val/calcFac(power)

    if terms == 1: return val
    else: return val + sinApprox(angle, terms - 1)

angle = int(input("Enter the angle to approximate (in radians): "))
terms = int(input("Enter the amount of terms to compute: "))
sinApprox(angle, terms)