【问题标题】:Approximating Sine recursively递归逼近正弦
【发布时间】:2018-03-28 02:38:37
【问题描述】:

所以我正在尝试编写一个包含两个递归函数的文件。其中之一计算通过泰勒级数逼近正弦所需的阶乘。第二个是另一个递归函数,它将正弦值输出为浮点值,并且将与输入的术语数量一样多。这是我想要得到的数学表示

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

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**) 

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

【问题讨论】:

  • 问题是什么?
  • 我需要帮助编写第二个函数,它将调用第一个函数(计算正弦近似值的阶乘部分)并将正弦近似值作为浮点值返回,并将继续用户输入的次数
  • 为什么一定要用递归?
  • 那么,如果您edit您的问题,您会得到一个“太宽泛”而不是“不清楚”的闭包。
  • 同时,这听起来真的像家庭作业(“必须”位)。如果你阅读了关于如何做的help center,就可以寻求家庭作业的帮助,所以如果是,你不必编故事。当然,如果你是从书本或其他东西中自学,那也没关系。

标签: python recursion series trigonometry


【解决方案1】:

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

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 2012-12-03
    • 1970-01-01
    相关资源
    最近更新 更多