帮助解决Lua Cosine的问题,返回了错误的结果。

首先,我不是在为课堂、考试或其他学生性质的活动写作。

我是一个游戏脚本程序员,正在尝试实现数学库供所有人使用,但遗憾的是,我只有非常基本的 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...(基于科学模式计算或使用在线工具计算cos(90)) 。

我还遇到了 sin 和 tan 的问题,但是它们的编写方式与cos类似,似乎已在许多语言中完成。如果我能弄清我做错了什么,我就能得到它们所有的修复。

编辑:更正了错字。

原文链接 https://stackoverflow.com/questions/3981402

点赞
stackoverflow用户156521
stackoverflow用户156521

首先,你的Lua脚本无法运行。其次,你需要将变量声明为局部变量。第三,cosine起始于[one](http://en.wikipedia.org/wiki/Taylor_series#List_of_Maclaurin_series_of_some_common_functions)。

这个问题是因为您使用的Taylor级数仅在接近零的正确余弦值上收敛。您将不得不使用更多的级数才能使其正确处理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

或者-查找或实现Lua中的[fmod](http://www.cplusplus.com/reference/clibrary/cmath/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版权所有(C)1994-2008 Lua.org,PUC-Rio

print(math.cos(90)) -0.44807359244883

2010-10-20 20:12:40