2

如果我在字符串中有一个公式x = y + (10/2) * 6(它是动态的,所以不一定是这样)并且我知道x = 5. 如何计算价值y

4

3 回答 3

3

你可以使用像dentaku这样的解析器

require 'dentaku'

calculator = Dentaku::Calculator.new
calculator.evaluate('10 * 2')
# => 20
calculator.evaluate('kiwi + 5', :kiwi => 2)
# => 7
于 2013-11-10T19:28:41.740 回答
2

Wolfram Alpha有一个免费的(需要注册的)API。甚至有人用它制作了宝石

于 2013-11-11T01:34:58.180 回答
1

你可以使用微积分

001:0> require 'calculus'
true
002:0> exp = Calculus::Expression.new("2 + 3 * x")
#<Expression:f46e77a9377ed2d5a9da768496a7e1c20be51bfe postfix_notation=[2, 3, "x", :mul, :plus] variables={"x"=>nil}>
003:0> exp.postfix_notation
[2, 3, "x", :mul, :plus]
004:0> exp.abstract_syntax_tree
[:plus, 2, [:mul, 3, "x"]]
005:0> exp.variables
["x"]
006:0> exp.unbound_variables
["x"]
007:0> exp["x"] = 5
5
008:0> exp.unbound_variables
[]
009:0> exp.calculate
17
于 2013-11-10T19:40:04.163 回答