python - 如何从 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)
解决方案
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 函数的一种特别有效的方法。
推荐阅读
- r - 如何拆分和重新排列列表
- python - Why does changing my desktop through python result in a red wallpaper?
- ios - 列表项内的按钮无法正常工作
- json - 使用 jq 从 swagger json 中提取路径、方法和内容类型
- javascript - How to fetch data between two dates using axios library
- php - CodeIgniter 4中错误验证时未定义的变量
- c# - 实现适当的 GetHashCode 类函数的策略
- c++ - 使用模板结构作为构造函数参数
- javascript - Android webview: how to obtain result of evaluateJavascript in a method that invokes evaluateJavascript?
- android - 如何正确更改 SparseArray 上的 HashMap?