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.

Public final class Mathnumber {    private mathnumber () {    } public     static String Numberpattern = "[-]?[ 0-9]+ ([.] [0-9]*)? ";    public static Pattern pattern = Pattern.compile (Numberpattern);     public static Matcher match (string string) {        Matcher match = Pattern.matcher (string);        if (Match.find ()) {            return match;        }        throw new RuntimeException (string + "is not a number.");}    

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.

public static String eval (string string) {string = String.Trim ();            while (!ismathnumber (string)) {////the same priority which first finds which System.out.println ("solve the equation:" + string);            Boolean found = false;                for (Mathinterface math:mathlist) {Matcher Matcher = Math.match (string);                    if (Matcher.find ()) {String exp = matcher.group ();                    String sig = "";                    if (Exp.charat (0) = = '-' && matcher.start ()! = 0) {//If it is not the first number,-the number can only be used when the operator sig = "+";                    } System.out.println ("Discovery formula:" + exp);                    String Evalresult = Math.eval (exp); string = string.substring (0, Matcher.start ()) + sig + Evalresult + string.substring (matcher.end                    ());                    SYSTEM.OUT.PRINTLN (exp + "evaluates to:" + Evalresult + ", substituting back to original");                    Found = true;                Break}} if (!found) {throw new RuntimeException (string + "is not a valid mathematical expression");    }} return string; }


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.

Addmathexpression (New Add ()); Addmathexpression (New Subtract ()); Addmathexpression (New Multiply ()); Addmathexpression (New Devide ()); Addmathexpression (new Minus ()); Addmathexpression (new factorial ()); Addmathexpression (new remainder ()); Addmathexpression (new bracket ()); Addmathexpression (New Power ()); 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.

public class Add implements Mathinterface {static String Pluspattern = blank + Mathnumber.numberpattern + blank    + "[+]{1}" + blank + mathnumber.numberpattern + blank;    Static pattern pattern = Pattern.compile (Pluspattern);     static Pattern plus = Pattern.compile (BLANK + "\\+");    @Override Public Matcher Match (string string) {return Pattern.matcher (string);    } @Override public int priority () {return 1;        } @Override public String eval (string expression) {Matcher A = MathNumber.pattern.matcher (expression);        if (A.find ()) {expression = Expression.substring (A.end ());        } Matcher p = plus.matcher (expression);        if (P.find ()) {expression = Expression.substring (P.end ());        } Matcher B = MathNumber.pattern.matcher (expression); if (B.find ()) {} return new BigDecimal (A.group ()). Add (New BigDecimal (B.group ())). ToString (    ); } }


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.

public class Bracket implements Mathinterface {     static String Bracketpattern = BLANK + "[(]{1}[^ (]*?[)]" + BLANK;    Static pattern pattern = Pattern.compile (Bracketpattern);     @Override Public    Matcher Match (String string) {        return Pattern.matcher (string);    }     @Override Public    int priority () {        return integer.max_value;    }     @Override public    String eval (string expression) {        expression = Expression.trim ();        Return Mathevaluation.eval (expression.substring (1,                expression.length ()-1));}    }


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

public static void Main (string[] args) {string string = "1+2^ (4/2) +5%2"; SYSTEM.OUT.PRINTLN ("The result is:" + mathevaluation.eval (String));}


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

Solution equation: 1+2^ (4/2) +5%2 found the equation: (4/2) solve the equation: 4/2 found the equation: The 4/24/2 calculation results are: 2.00, substituting the original (4/2) calculated as: 2.00, substituting the original formula: 1+2^2.00+5%2 found the formula: 2^ 2.002^2.00 calculation results are: 4, the generation of the original formula: 1+4+5%2 found the formula: 5%25%2 calculated as: 1, the generation of the original formula: 1+4+1 found the formula: 1+41+4 calculated as: 5, the return of the original formula: 5+1 the formula: 5+15+ 1 The result of the calculation is: 6, the return of the original 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

Please click Watch, Star, fork in the upper right cornerto become unwatch, Unstar, Unfork ( if the tiny project does not fork to the user space, the following clone command will be faulted ), To support the development of tiny framework!

Welcome to the Open source technology community: http://bbs.tinygroup.org . The Code and framework information in this example will be shared in the community. "Self-write framework" member QQ Group: 228977971, let us work together to understand the mystery of the open source framework!

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

Related Article

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.