以逻辑方式求解方程的问题
我正在考虑一种用简单的面向对象来求解简单方程的方法。我发现了一种方法,它似乎适用于变量单独存在的所有情况。请参阅:
例如,此方程:(4 / x + 3) / 2 = 2
首先,我将减号运算符 ((4 / x + 3) / 2 - 2 = 0
) 中的等于转换为等于零。 然后,我按正常优先顺序应用所有操作,就像 x
变成数字一样。第一个是4 / x
,我将操作4/
放入堆栈并返回x。接下来是x + 3
(记住4 / x
结果是x
)。操作进入堆栈(现在是 4/ +3
)并返回 x
。重新计算,最终堆栈将是 4/ +3 /2 -2
。然后我按以下顺序恢复所有操作:
+n --> -n
-n --> +n
*n --> /n
/n --> *n
n/ --> n/
**n --> **(1/n)
(where the missing value of these binary operations is the variable)
现在堆栈为 4/ -3 *2 +2。现在我颠倒顺序并将所有操作应用到零:
Stack: +2 *2 -3 4/ 运算:4 / ((0 + 2) * 2 - 3)
结果是 4,即 x
的值。
这是非常令人困惑和复杂的,但是是合乎逻辑的,并且很容易用 ruby 编写代码来在任何方程中执行该代码:
class Variable
# define all numeric operators to use the stack and return self
end
def solve
x = Variable.new
yield(x)
return x.value
end
x = solve do |x|
(4 / x + 3) / 2 == 2
end
它的最终界面非常酷。
但我的问题是:如何以这种方式解决x + x == 4
?也就是说,如何将两个变量栈相加呢?
I was thinking about a way to solve simple equations with simple object orientation. I found a method that appears to works in all cases where the variable is alone. See:
For sample, this equation: (4 / x + 3) / 2 = 2
First I convert the equal in a minus operator ((4 / x + 3) / 2 - 2 = 0
) to equaly everything to zero.
Then I apply all operations in normal precedence order, exactly as if x
becomes a number. The first one is 4 / x
, I put on stack the operation: 4/
and return x. The next is x + 3
(remeber that 4 / x
resulted in x
). The operations goes to the stack (now is 4/ +3
) and returns x
. Remeating this the final stack will be 4/ +3 /2 -2
. Then I revert all operations in this order:
+n --> -n
-n --> +n
*n --> /n
/n --> *n
n/ --> n/
**n --> **(1/n)
(where the missing value of these binary operations is the variable)
Now the stack is 4/ -3 *2 +2
. Now I reverse the order and apply all operations to zero:
Stack: +2 *2 -3 4/
Operation: 4 / ((0 + 2) * 2 - 3)
The result is four, the value of x
.
This is very confuse and complex, but is logical and is easy to make a code in ruby that executes that in any equation:
class Variable
# define all numeric operators to use the stack and return self
end
def solve
x = Variable.new
yield(x)
return x.value
end
x = solve do |x|
(4 / x + 3) / 2 == 2
end
The final interface of this is very cool.
But my problem is that: How to solve x + x == 4
in this way? In other words, how to add two variable stacks?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据要求,我将之前的评论作为答案:
为此,您不需要两个变量堆栈。您需要一个简化阶段,将其更改为
2x = 4
,然后求解x
。为了扩展这一点,第一步是进行一些符号计算,例如术语重写和简化。一旦你有了这个,使用你当前的解算器(不过请记住路易斯在他的评论中所说的)。
As requested I'm making my previous comment an answer:
You don't need two variable stacks for this. You need a simplifying stage that changes this to
2x = 4
and then solves forx
.To expand on that, a first step that does some symbolic computation like term rewriting and simplification would be in order. Once you have that, use your current solver (keep in mind what Luis said in his comments though).