帮助解决Lua Cosine的问题,返回了错误的结果。
2010-10-20 21:2:3
收藏:0
阅读:151
评论:1
首先,我不是在为课堂、考试或其他学生性质的活动写作。
我是一个游戏脚本程序员,正在尝试实现数学库供所有人使用,但遗憾的是,我只有非常基本的 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
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
- 如何编写 Lua 模式将字符串(嵌套数组)转换为真正的数组?
首先,你的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