Math 使用Lua余弦进行协助,返回错误结果

Math 使用Lua余弦进行协助,返回错误结果,math,scripting,lua,trigonometry,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

好的,首先,这不是针对课堂、考试或其他学生类型的活动。

我是一名游戏脚本编写员,我正在尝试实现供所有人使用的数学库,不幸的是,我所拥有的只是非常基本的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
问题是,对于这些函数,print(math.cos(90))返回4.77135。。。当我期待-0.44807。。。(基于科学模式下的计算,或使用在线工具计算cos(90))

我也有一些关于sin和tan的问题,但是它们同样是写给cos的,这似乎是用很多语言写的。如果我能找出我做错了什么,我就能把它们都修好


编辑:更正输入错误首先,您的lua无法运行。其次,您需要将变量设置为局部变量。第三,余弦以a开头

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

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


只是想澄清一下,你们并没有访问Lua的标准数学库的权限?这是个棘手的问题。我花了一段时间才发现这个问题。ponzao,没错,没有数学库。。或者字符串、位、表,甚至“标准”(提供解包的那个)。我正在首先实现数学库,因为它对游戏中的脚本编写影响最大。作为其他用户的脚本编写者用户,在复制之前,我已经开始在源代码中键入易于阅读的版本,但忘记了修复它。应该是“math.cos=function(b,p)e=0”…好的,检查它,检查它的工作情况,并返回正确的值。从大学开始,我就没有深入接触过数学,我发现它不像骑自行车。非常感谢你的帮助。现在,是时候把它作为罪和其他罪的基础了。
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
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
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 
imac:~ root$ lua -i temp.lua 
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> print( math.cos( 90 ) )
-0.44807359244883
>