Lua学习笔记
2016-01-27 10:37
507 查看
Lua练习题:
不采用幂的方式进行多项式的求和。最多采用n次的乘法和n次的加法实现给定多项式系数和x值的求和。
代码:
结果如下所示:
不采用幂的方式进行多项式的求和。最多采用n次的乘法和n次的加法实现给定多项式系数和x值的求和。
代码:
Exercise 3.4: Can you write a function from the previous -- item so that it uses at most n additions and n multiplications -- (and no exponentiations)? -- coefficients are stored in a Lua array, -- with the first array member representing -- the first coefficient (which is multiplied -- by x^n) and the last array member representing -- the last coefficient (multiplied by x) <span style="display: none; width: 0px; height: 0px;" id="transmark"></span> -- calculates polynomials using 2n multiplications, -- n additions and no exponentiations or something -- along those lines function calculate(coefficients, x) p = 0 cur = 1 for i = #coefficients, 1, -1 do--幂是降次幂 p = p + cur*coefficients[i]--coefficients[#coefficients]存放的系数对应的幂是最低的, cur = cur * x--幂通过每次乘以x实现。类似递推的方式进行 end return p end -- read coefficients from user print("how many coefficients should be read?") size = io.read("*n") print("reading " .. size .. " coefficients") c = {} for i = 1, size do c[#c+1] = io.read("*n") end -- asks for x values to calculate the function print("please enter x values (ctrl-d to exit)") while true do x = io.read("*n") print("f(" .. x .. ") = " .. calculate(c, x)) end
结果如下所示:
相关文章推荐
- Lua 迭代器
- Lua按指定字符分隔字符串的3种方法
- 初识 love2d. Hello World & lua 调试 & iOS 环境运行
- 使用lua代码创建文件夹,解压zip文件到指定目录(亲测可用)
- lua io函数
- lua os函数
- lua table函数
- lua重要函数
- Lua string函数说明
- lua 字符串模式匹配
- 为什么 Lua 的新版本越来越慢?
- LUAMD5加密
- LUAMD5加密
- Lua学习笔记(函数)
- lua与游戏测试(二)
- lua 与游戏测试 (一)
- lua的table库中经常使用的函数
- lua之m进制转换为n进制-任意进制转换算法
- quicklua随机数
- 机器学习模型评价(Evaluating Machine Learning Models)-主要概念与陷阱