V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
爱意满满的作品展示区。
ototsuyume
V2EX  ›  分享创造

用python写了个解方程的脚本

  •  
  •   ototsuyume · 2012-04-29 21:39:06 +08:00 · 4842 次点击
    这是一个创建于 4393 天前的主题,其中的信息可能已经有所发展或是发生改变。
    地址:https://github.com/ototsuyume/function-s-root

    先把输入的方程解析成语法树,然后求导数,再用牛顿迭代法循环求解,例如:
    ./parse.py "x^2-20000"
    ['x', '^', '2', '-', '20000']
    <expr.sub_expr object at 0x108301510>
    ('before differention:', '(x^(2))-20000')
    ('Differention:', '1*2*(x^(1))-0')
    ('Simplify:', '2*x')
    Iterating times:1 value:10000.500000
    Iterating times:2 value:5001.249950
    Iterating times:3 value:2502.624475
    Iterating times:4 value:1255.308043
    Iterating times:5 value:635.620194
    Iterating times:6 value:333.542762
    Iterating times:7 value:196.752544
    Iterating times:8 value:149.201536
    Iterating times:9 value:141.624207
    Iterating times:10 value:141.421502
    Iterating times:11 value:141.421356
    The root of the function is:141.421356

    存在一个问题是不知道怎么找出第一次迭代时比较好的x值,用随机数发现很容易超出python的整数范围,于是设了初始值为1,看来对大部分的方程都有效,hmmmmmm

    比较少用python,代码风格或许不好,望轻喷
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   992 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 21:50 · PVG 05:50 · LAX 14:50 · JFK 17:50
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.