math - 协助 Lua Cosine,返回错误结果

标签 math scripting lua trigonometry

好的,首先,这不适用于类、测试或其他学生类型的事件。

我是游戏的脚本编写者,正在尝试实现供所有人使用的数学库,不幸的是,我所能使用的只是非常基本的 lua。实现的版本不能更改,并且不包含任何库。对于那些想知道的人,它用于在 Fold.It 中编写脚本。

这是我所拥有的...

math={}
math.fact = function(b) if(b==1)or(b==0) then return 1 end e=1 for c=b,1,-1 do e=e*c end return e end
math.pow = function(b,p) e=b if(p==0) then return 1 end if(p<0) then p=p*(-1) end for c=p,2,-1 do e=e*b end return e end
math.cos = function(b,p) e=0 p=p or 10 for i=1,p do e=e+(math.pow(-1,i)*math.pow(b,2*i)/math.fact(2*i)) end return e end

为了澄清上述内容,math.fact 返回阶乘,它返回精确到大约 10 点的精度,并且是我为辅助余弦计算所做的新函数。

math.pow 也是一个处理返回幂的新函数,也按预期工作。

问题在于余弦函数。它返回意外的值。这是一个更容易消化的版本(我一直在写我的库内容超精简)...
function math.cos(value,precision) 
    result=0 
    precision=precision or 10 
    for i=1,precision do 
        result=result+(math.pow(-1,i)*math.pow(value,2*i)/math.fact(2*i)) 
    end 
    return e 
end

问题是,对于这些函数,对于 print(math.cos(90)) 它返回 4.77135... 当我期待 -0.44807...(基于科学模式下的 calc,或使用在线工具来计算 cos( 90))。

我也有 sin 和 tan 的问题,但是它们类似地写入 cos,这似乎已用多种语言完成。如果我能弄清楚我做错了什么,我可以把它们全部修复。

编辑:更正错字

最佳答案

首先,你的 lua 没有运行。其次,您需要将变量设为本地变量。第三,余弦以 one 开头.

问题是因为您使用的泰勒级数仅收敛于接近零的正确余弦值。您必须使用该系列的更多术语才能正确处理 90。您可以通过两种方式为您的实现修复此问题:

添加 pi 常数。然后使用 while 循环调整值,使 abs(value) < 2*pi:

math.pi = 3.14159265358
while value > math.pi*2 do 
  value = value - math.pi * 2 
end
while value < -math.pi*2 do
  value = value + math.pi * 2
end

或者 - 查找或实现 fmod 的版本在卢阿。

这是更正后的代码(您可以缩小它):
math={}
math.fact = function(b)
    if(b==1)or(b==0) then
        return 1
    end
    local e=1
    for c=b,1,-1 do
        e=e*c
    end
    return e
end

math.pow = function(b,p)
    local e=b
    if(p==0) then
        return 1
    end
    if(p<0) then
        p=p*(-1)
    end
    for c=p,2,-1 do
        e=e*b
    end
    return e
end
math.cos = function(b,p)
    local e=1 
    b = math.correctRadians(b) 
    p=p or 10
    for i=1,p do
        e=e+(math.pow(-1,i)*math.pow(b,2*i)/math.fact(2*i))
    end
    return e
end

math.pi = 3.1415926545358
math.correctRadians = function( value )
    while value > math.pi*2 do
        value = value - math.pi * 2
    end           
    while value < -math.pi*2 do
        value = value + math.pi * 2
    end 
    return value
end 

交互式lua运行:
imac:~ root$ lua -i temp.lua 
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> print( math.cos( 90 ) )
-0.44807359244883
> 

关于math - 协助 Lua Cosine,返回错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3981402/

相关文章:

c++ - 求小数位数总和的最快方法

python - 通过 Python 但通过 Linux 命令终端调用 MATLAB

javascript - 用变量替换 css 属性

lua - Redis Lua 不识别 Inf?

lua - 推送可执行函数指针?

c++ - 当函数几乎为 "flat"时,牛顿-拉夫森方法不可能实现

python - python中一组项目的所有可能顺序的列表

algorithm - 最高效的马尔可夫链算法

c# - 将 Lua 与 C#/Mono 结合使用

c - 使用 C 函数 notify_notification_update() 的段错误