Package jmathexpr.arithmetic.rule

Source Code of jmathexpr.arithmetic.rule.Rationalization$SqrtDenominator

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package jmathexpr.arithmetic.rule;

import jmathexpr.Expression;
import jmathexpr.arithmetic.func.Sqrt;
import jmathexpr.arithmetic.op.Division;
import jmathexpr.arithmetic.op.Multiplication;
import jmathexpr.arithmetic.pattern.FractionPattern;
import jmathexpr.util.pattern.AnyPattern;
import jmathexpr.util.rule.CompositeRule;
import jmathexpr.util.rule.SubRule;

/**
* Rule for rationalizing an expression. E.g. removing a square root from a fraction's
* denominator.
*
* @author Elemér Furka
*/
public class Rationalization extends CompositeRule {
   
    private final FractionPattern fraction = new FractionPattern();
   
    /**
     * Creates a new recursive rule.
     */
    public Rationalization() {
        super(true);
    }

    @Override
    public boolean matches(Expression expr) {
        if ((rule = new SqrtDenominator()).matches(expr)) return true;

        return false;
    }

    /**
     * a / sqrt(b) = a sqrt(b) / b
     */
    private class SqrtDenominator extends SubRule {
       
        private final AnyPattern arg = new AnyPattern();
        private final Sqrt pattern = new Sqrt(arg);

        @Override
        public boolean matches(Expression expr) {
            return fraction.matches(expr) && pattern.matches(fraction.denominator());
        }

        @Override
        public Expression apply() {
            Expression sqrt = new Sqrt(arg.hit());
           
            return new Division(new Multiplication(fraction.numerator(), sqrt),
                       new Multiplication(fraction.denominator(), sqrt));
        }
    }
}
TOP

Related Classes of jmathexpr.arithmetic.rule.Rationalization$SqrtDenominator

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.