Open source framework That thing 14: teaching computer programs to solve math problems

Source: Internet
Author: User

Weekend, looking at the expert system of the book, which has about the rules of the content, suddenly think, can imitate people's learning way to improve computer program computing ability?

Imagine, a little child, he started nothing, first of all, you have to tell him what is the number, and then tell him what is to add, subtract, and then tell him what is multiply, divide, and tell him that the multiplication, in addition to calculate the multiplication first, and then introduced the parentheses, the parentheses are always the first to calculate parentheses. Thus, the more skills he has to tell him, the more he will be able to solve the problem.
So I tried to experiment with it.
The first step is to teach the computer to learn what numbers are.
The following regular expression, is to tell the "child", the number is the front may have "-" number, of course, may not, the next consecutive number 0-9, the number of the composition, there may also be a decimal point to start adding a heap of 0-9 numbers, of course, there is no relationship. So, it even knows how to recognize numbers.

[Java]View Plaincopy
  1. Public Final class Mathnumber {
  2. Private Mathnumber () {
  3. }
  4. public static String Numberpattern = "[-]?[ 0-9]+ ([.] [0-9]*)? ";
  5. public static pattern pattern = Pattern.compile (Numberpattern);
  6. public static Matcher match (string string) {
  7. Matcher match = Pattern.matcher (string);
  8. if (Match.find ()) {
  9. return match;
  10. }
  11. throw New RuntimeException (string + "is not a number.");
  12. }
  13. }

The second step is to tell the child, the process of calculating the maths problem.
If there is a space on both sides, ignore it, then, see if it is already a number, if it is a number, it means that even if the result. If not, start with the highest priority and calculate if you find it. If you can't find it, it means there is a problem, not a valid mathematical formula.

[Java]View Plaincopy
  1. Public static String eval (string string) {
  2. string = String.Trim ();
  3. While (!ismathnumber (String)) {//the same priority which first found which
  4. System.out.println ("solution formula:" + string);
  5. Boolean found = false;
  6. For (Mathinterface math:mathlist) {
  7. Matcher Matcher = Math.match (string);
  8. if (Matcher.find ()) {
  9. String exp = Matcher.group ();
  10. String sig = "";
  11. if (Exp.charat (0) = = '-' && matcher.start ()! = 0) {//If it is not the first number, the-number can only be used as an operator
  12. sig = "+";
  13. }
  14. System.out.println ("Discovery formula:" + exp);
  15. String Evalresult = Math.eval (exp);
  16. String = String.substring (0, Matcher.start ()) + sig
  17. + Evalresult + string.substring (Matcher.end ());
  18. SYSTEM.OUT.PRINTLN (exp + "evaluates to:" + Evalresult + ", substituting back to original");
  19. Found = true;
  20. Break ;
  21. }
  22. }
  23. if (!found) {
  24. throw New RuntimeException (string + "not a valid mathematical expression");
  25. }
  26. }
  27. return string;
  28. }


From now on, the child has been able to solve the problem, but he still do not understand, he still do not know what is added, minus, multiply, except what, there is no way, the child stupid, as long as teach him more.
Below teaches him how to calculate, add, subtract, multiply, divide, remainder, parentheses, exponent.

[Java]View Plaincopy
  1. Addmathexpression (new Add ());
  2. Addmathexpression (new Subtract ());
  3. Addmathexpression (new Multiply ());
  4. Addmathexpression (new Devide ());
  5. Addmathexpression (new Minus ());
  6. Addmathexpression (new factorial ());
  7. Addmathexpression (new Remainder ());
  8. Addmathexpression (new bracket ());
  9. Addmathexpression (new Power ());
  10. Collections.sort (Mathlist, new Mathcomparator ());


Because of the same similarity, it is only the implementation of the addition and parentheses.
The addition implementation, its priority is 1, it is composed of two numbers in the middle plus a "+" number, the number and the plus sign in front of the space is useless, do not care about it. Calculate the time, is to add the way to add two numbers, this computer is stronger than people, hehe, tell him how to add will never be wrong. and understand that subtraction has an innate advantage.

[Java]View Plaincopy
  1. Public class Add implements Mathinterface {
  2. static String Pluspattern = blank + mathnumber.numberpattern + blank
  3. + "[+]{1}" + blank + mathnumber.numberpattern + blank;
  4. static Pattern pattern = Pattern.compile (Pluspattern);
  5. static Pattern plus = Pattern.compile (BLANK + "\\+");
  6. @Override
  7. Public Matcher Match (String string) {
  8. return Pattern.matcher (string);
  9. }
  10. @Override
  11. Public int priority () {
  12. return 1;
  13. }
  14. @Override
  15. Public String eval (string expression) {
  16. Matcher a = MathNumber.pattern.matcher (expression);
  17. if (A.find ()) {
  18. expression = expression.substring (A.end ());
  19. }
  20. Matcher p = plus.matcher (expression);
  21. if (P.find ()) {
  22. expression = expression.substring (P.end ());
  23. }
  24. Matcher B = MathNumber.pattern.matcher (expression);
  25. if (B.find ()) {
  26. }
  27. return New BigDecimal (A.group ()). Add (new BigDecimal (B.group () ))
  28. . toString ();
  29. }
  30. }


Next is the parentheses, the parentheses are the highest priority, as long as it should be calculated first. Of course, the contents of the inner parentheses are calculated first. Parentheses in the content, when the calculation, you can first pull out, no tube outside the content, calculated, put back on it.

[Java]View Plaincopy
  1. Public class Bracket implements Mathinterface {
  2. static String Bracketpattern = blank + "[(]{1}[^ (]*?[)]" + blank;
  3. static Pattern pattern = Pattern.compile (Bracketpattern);
  4. @Override
  5. Public Matcher Match (String string) {
  6. return Pattern.matcher (string);
  7. }
  8. @Override
  9. Public int priority () {
  10. return integer.max_value;
  11. }
  12. @Override
  13. Public String eval (string expression) {
  14. expression = Expression.trim ();
  15. return Mathevaluation.eval (expression.substring (1,
  16. Expression.length ()- 1));
  17. }
  18. }


So far, our program "Baby" has learned mathematical calculations, a question let Iraq try.

[Java]View Plaincopy
    1. Public static void Main (string[] args) {
    2. String string = "1+2^ (4/2) +5%2";
    3. System.out.println ("The result is:" + mathevaluation.eval (string));
    4. }


The procedure for your baby's problem is as follows:

[Java]View Plaincopy
  1. Solution equation:1+2^ (4/2) +5%2
  2. Discovery Formula: (4/2)
  3. Solve equation:4/2
  4. Discovery equation:4/2
  5. 4/2 calculated as:2.00, back to the original type
  6. (4/2) calculated as:2.00, back to the original type
  7. Solution equation:1+2^2.00+5%2
  8. Discovery formula:2^2.00
  9. 2^2.00 Calculates the result:4, substituting the original type
  10. Solution equation:1+4+5%2
  11. Discovery formula:5%2
  12. 5%2 Calculates the result:1, substituting the original type
  13. Solution equation:1+4+1
  14. Discovery formula:1+4
  15. 1+4 Calculates the result:5, substituting the original type
  16. Solution equation:5+1
  17. Discovery formula:5+1
  18. 5+1 Calculates the result:6, substituting the original type
  19. The result is:6


Hehe, the program baby's problem-solving process is very consistent with the process of human being, and the implementation of the program is very easy to understand. God horse compilation principle, God horse infix expression is not used. (Execution efficiency is not necessarily high compared to other algorithms, and is only used to verify that the program's processing power is enhanced through rules, and that the regular expressions and program logic are not rigorously written without deep validation due to no in-depth testing)

In fact, although the program is very simple, but, in fact, is a simple rule of the prototype engine.
First, he loads a lot of business processing rules, plus, minus, multiply, divide, interpolate, index, remainder and so on.
Second, his business rules can be extended continuously.
Thirdly, as long as the facts are given, finally, by the constant application of the rules, he will eventually export the result, either the correct result or the fact that it is wrong.

For children who need the source code, please go to git and get the codes directly.

Git address: http://git.oschina.net/tinyframework/mathexp.git

Open source framework That thing 14: teaching computer programs to solve math problems

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.