001import org.apache.commons.math3.analysis.UnivariateFunction; 002 003/** Wrapper used to pass a method definition to <a target="_blank" href="http://commons.apache.org/math">Commons Math</a> algorithms. 004 * Computes a command given as a String.<br/> 005 * <br/> 006 * See <a target="_top" href="../0_CommonsMath_README.html#examples">JxnUnivariateFunction_SolverOptimizer~Demo.jxn</a> 007 * for examples. 008 */ 009public class JxnUnivariateFunction implements UnivariateFunction 010{ 011 String cmd; 012 KmgFormelInterpreter fi; 013 static final boolean skipInputLogEnabled = true; 014 015 /** Constructs an {@link org.apache.commons.math3.analysis.UnivariateFunction} 016 * instance to be used by <a target="_blank" href="http://commons.apache.org/math">Commons Math</a> algorithms.<br/> 017 * Example: 018 * <pre> 019 * uvf = @JxnUnivariateFunction( $this, "Math.sin $x;" )</pre> 020 * @param fi an internal copy of {@code fi} is used to execute {@code cmd} 021 * @param cmd one or more statements separated by '{@code ;}'. The command {@code cmd} must use the 022 * variable double {@code $x} 023 * to compute a result of type double. If {@code cmd} ends with '{@code ;}', log output of intermediate steps is suppressed. 024 */ 025 public JxnUnivariateFunction( KmgFormelInterpreter fi, String cmd ) 026 { 027 this.cmd = cmd; 028 this.fi = new KmgFormelInterpreter( fi ); 029 } 030 031 /** @deprecated replaced by {@link #JxnUnivariateFunction(KmgFormelInterpreter, String)} */ 032 public JxnUnivariateFunction( String cmd, KmgFormelInterpreter fi ) 033 { 034 this.cmd = cmd; 035 this.fi = new KmgFormelInterpreter( fi ); 036 } 037 038 /** Internally called by Commons Math algorithms: Computes the function value using the given argument {@code x}. */ 039 public double value( double x ) 040 { 041 fi.put( "$x", new JxnPrimitiveWrapper(x) ); 042 return KmgFormelInterpreter.doubleValue( fi.execute( cmd, skipInputLogEnabled ) ); 043 } 044 045 /** Returns the command {@code cmd} passed to the constructor. */ 046 public String toString() 047 { 048 return cmd; 049 } 050}