简体   繁体   English

符号和数值计算

[英]Symbolic & Numeric Calculation

I'm a Computer Science student, on last semester we learned to program in Prolog. 我是计算机科学专业的学生,​​上学期我们学会了在Prolog中编程。 Now I'm trying to have fun with it. 现在,我想尝试一下。 I'm trying to build a program that given a symbolic/mathematical input it return the result. 我正在尝试构建一个给出符号/数学输入的程序,它返回结果。 example: 例:

? solve(2+3+Z+K+5+Z+1, R).
R = 11+2*Z+K or R = 11+Z+K+Z

This is the snippet (for + operation) 这是代码段(用于+操作)

solve(X, R) :-
    eval(X, R).

eval(X, X) :- var(X),!.
eval(X, X) :- number(X), !.  
eval(+(X, Y), R) :-
    eval(X, A),
    eval(Y, B),
    add(A, B, R), !.

add(A, B, R) :-
    number(A),
    number(B),
    !,
    R is A + B.
add(A, B, A+B) :-
    var(A); var(B),!.
add(A+X, B, R+X) :-
    number(A),
    number(B),
    var(X),
    !,
    R is A + B.
add(X+A, B, R+X) :-
    number(A),
    number(B),
    var(X),
    !,
    R is A + B.

I have some issue when numbers are separated by many variables, example: 当数字由许多变量分开时,我遇到一些问题,例如:

? solve(5+Z+5+4+K+Z+6, R).
FALSE.

or, (not form source code above), if numbers are separated by many variables, they are not "processed", example: 或(如果不是用上面的源代码形式的话),如果数字被许多变量分开,则它们不会被“处理”,例如:

? solve(5+Z+K+7, R).
R = 5+Z+K+7.

Thanks for help, any suggestion or reference will be appreciate. 感谢您的帮助,任何建议或参考将不胜感激。

This is a bit more involved than what your code is doing at the moment. 这比您的代码目前正在做的事情要复杂得多。 At the end, you seem to want to have a solver for symbolic equations, is that so? 最后,您似乎想要一个符号方程的求解器,是吗? So for example, if you type into Wolfram Alfa your equation, 2+3+Z+K+5+Z+1 = R , you get the answer K+2 Z+11 = R . 因此,例如,如果您在Wolfram Alfa中键入方程2+3+Z+K+5+Z+1 = R ,则得出答案K+2 Z+11 = R

Similar functionality is provided for example by metafont: 例如,metafont提供了类似的功能:

$ mf
This is METAFONT, Version 2.7182818 (TeX Live 2014) (preloaded base=mf)
**\relax

*tracingequations:=tracingonline:=1;

*2+3+a+b+5+a+1=r;
## a=0.5r-0.5b-5.5

*x^2+3=0;
## x^2=-3

... and I guess by every program as Matlab, Mathematica, etc. ...而且我猜每个程序都包括Matlab,Mathematica等。

In Prolog, for integers, you get something very similar for free if you use library(clpfd) : 在Prolog中,对于整数,如果使用library(clpfd) ,您将免费获得非常相似的东西:

?- use_module(library(clpfd)).
true.

?- 2 + 3 + Z + K + Z + 1 #= R.
2*Z+K+ -1*R#= -6.

If you want to program this yourself, you should probably start with deciding how you want to represent your answers: as you see, the three programs demonstrated here choose different approaches. 如果您想自己编写程序,则可能应该先确定要如何表示答案:如您所见,此处演示的三个程序选择了不同的方法。 From there, you can either try to see how to get there yourself (see the comment by @lurker), or try to figure out how others have implemented it. 从那里,您可以尝试看看自己如何到达那里(请参阅@lurker的评论),也可以尝试弄清楚其他人如何实现它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM