| 赞 | 15 |
| VIP | |
| 好人卡 | |
| 积分 | 19 |
| 经验 | |
| 最后登录 | 2026-5-25 |
| 在线时间 | 404 小时 |
- 梦石
- 0
- 星屑
- 1944
- 在线时间
- 404 小时
- 注册时间
- 2015-8-30
- 回帖
- 322
|
加入我们,或者,欢迎回来。
您需要 登录 才可以下载或查看,没有账号?注册会员
×
本帖最后由 有丘直方 于 2018-8-13 21:52 编辑
去年6R关掉之后我就对于自己的账号里面的东西非常惋惜啊!
结果过了那么久才发现原来我的东西全都跑到这里(rpg.blue)来了!
真是相见恨晚!
刚刚瞎写了个解方程用的代码:- def solve(f, ini = 0, dx = 1.0e-8, eps = 1.0e-8, times = 100)
- res = ini
- times.times do
- x = res
- y = f.call(res)
- return res if y.abs <= eps
- res = linear_solve(*point_slope_to_linear_function(x, y, diff(f, x, dx)))
- end
- return
- end
- def diff(f, x, dx = 1.0e-8)
- d1 = (f.call(x) - f.call(x-dx)) / dx
- d2 = (f.call(x+dx) - f.call(x)) / dx
- (d1+d2) / 2
- end
- def linear_solve(k, b)
- -b/k
- end
- def point_slope_to_linear_function(x, y, k)
- [k, y-x*k]
- end
复制代码 使用Newton法。
使用方法:先定义一个提供call(x)方法的对象f作为函数,然后调用solve(f, ini)即可返回这个函数的实零点中距离ini最近的那个……
指定的dx和eps越小精度越高……
如果算出来方程无解可以尝试把times调大一点……
令我没想到的是写完这个代码居然测试一遍就成功……
测试用代码:- def function(x)
- 3*x**3-2*x**2+12*x-123
- end
- f = method(:function)
- p solve(f) # => 3.2726090206620366
复制代码 经过MATLAB检验,确实是正确的解,而且精度还挺高的…… |
评分
-
查看全部评分
|