首页 > 解决方案 > 如何从 CORDIC、泰勒级数或 Python 中的替代计算正弦/余弦/正切?

问题描述

我正在为数学函数创建一个库,旨在测试和挑战我的编程和数学技能。其中一个必要的部分是三角:正弦、余弦、正切和导数/倒数,使用​​度数或弧度。

我花了几个小时在网上搜索使用度数和/或弧度的泰勒级数或 CORDIC 算法的实现,但无济于事。

def sin(x):
    if numerics.degrad == 'deg':
        #compute sin(x) using degrees or radians, make sure to return the result in degrees

请注意, numerics.degrad 是要从库或终端中的任何函数引用的字符串值。通常的值为“度”或“弧度”。另外,我试图避免导入像 numpy 或 math 这样的库。

更新:我今天(11-12-19)尝试通过生成与一个波形相交的抛物线来模拟正弦波。希望是检查角度将落在哪个波形上,然后使用相应的二次方程。那没有用。DESMOS 中的结果最多相差 0.2 个单位,而我的 python 实现完全是错误的。

# desmos implementation, where y is the output and x is the angle:
# y=0.0001234567901234(x-90)^2+1
# lays closely over a sine wave graphed with y=sin(x).

# here is my python implementation:

def sin(anglein):    #return the result of sine of the supplied angle, using the mode
    if degrad == 'deg':
        const = 0.0001234567901234
        angle = anglein
        while angle > 360:    #should return the corresponding angle within 0-360 degrees
            angle -= 360

        return((const * ((angle - 90) * (angle - 90))) + 1)

标签: python

解决方案


sin 函数的泰勒级数很容易实现。请注意,除非另有说明,否则任何为三角函数提供泰勒级数的参考都将假定输入以弧度为单位。

PI = 3.141592653589793238462643383

def sin_taylor_series(x, terms=9):
    # map x into the range -PI/2 to PI/2 for greatest accuracy
    x %= 2*PI
    if x > PI:
        x -= 2*PI
        if x < -PI/2:
            x = -PI - x
    elif x > PI/2:
        x = PI - x

    total = 0
    denominator = 1
    for i in range(1, 2*terms+2, 2):
        denominator *= i
        total += (x ** i) / denominator
        denominator *= -(i + 1)
    return total

在 9 项中,最大绝对误差(与 相比math.sin)低于10 ** -15,这与将大量浮点数相加得到的结果差不多。

请注意,这不是逼近 sin 函数的一种特别有效的方法。


推荐阅读