package Math::Eval; use strict; use warnings; BEGIN { use Carp; my $dir; for(@INC) { if(-f "$_/Math/Eval.pm") { $dir="$_/Math/Eval"; mkdir($dir) unless(-d $dir); $dir.='/.Inline'; mkdir($dir) unless(-d $dir); last; } } if(eval{ require Inline }) { my @opts=( C => 'DATA', LIBS => '-lmatheval', ); push(@opts, DIRECTORY => $dir ) if($dir); Inline->import(@opts); } else { croak("Inline not installed!"); } } our $VERSION="1.0"; sub parse{&new} sub evaluate { my $self=shift; my $vals={}; if(ref($_[0]) && ref($_[0]) eq 'HASH') { $vals=shift; } elsif(@_) { pop(@_) if(@_%2); $vals={@_}; } return $self->_evaluate($vals); } 1; __DATA__ __C__ #include SV* new(SV* ref, char* buffer) { char* class; if (sv_isobject(ref)) { class = (char *)sv_reftype(SvRV(ref), 1); } else { if (!SvPOK(ref)) { croak("Need an object or class name as first argument"); } class = SvPV_nolen(ref); } void* f = evaluator_create (buffer); if(f==NULL) { return &PL_sv_undef; } SV* obj_ref = newSViv(0); SV* obj = newSVrv(obj_ref, class); sv_setnv(obj, (IV)f); SvREADONLY_on(obj); return obj_ref; } SV* derivative(SV* obj, char* name) { char* class; if (sv_isobject(obj)) { class = sv_reftype(SvRV(obj), 1); } else { croak("Need an object as first argument"); } void* f=evaluator_derivative((void*)SvIV(SvRV(obj)), name); if(f==NULL) { return &PL_sv_undef; } SV* obj_n_ref = newSViv(0); SV* obj_n = newSVrv(obj_n_ref, class); sv_setnv(obj_n, (IV)f); SvREADONLY_on(obj_n); return obj_n_ref; } void get_variables(SV* obj) { if (!sv_isobject(obj)) { croak("Need an object as first argument"); } char** names; int count; evaluator_get_variables ((void*)SvIV(SvRV(obj)), &names, &count); Inline_Stack_Vars; Inline_Stack_Reset; int i; for (i = 0; i < count; i++) { Inline_Stack_Push(sv_2mortal(newSVpv(names[i],0))); } Inline_Stack_Done; } char* get_string(SV* obj) { if (!sv_isobject(obj)) { croak("Need an object as first argument"); } return evaluator_get_string((void*)SvIV(SvRV(obj))); } double _evaluate(SV* obj, SV* ref) { if (!sv_isobject(obj)) { croak("Need an object as first argument"); } char** names; int count; evaluator_get_variables ((void*)SvIV(SvRV(obj)), &names, &count); double values[count]; char* c_key; double c_val; SV **svp; int i; HV* hash=(HV *) SvRV(ref); int num_keys = 0; for (i = 0; i < count; i++) { c_key=names[i]; svp=hv_fetch(hash,c_key,strlen(c_key),0); if(svp) { num_keys++; c_val=SvNV(*svp); values[i]=c_val; } } return evaluator_evaluate((void*)SvIV(SvRV(obj)),num_keys,names,values); } void DESTROY(SV* obj) { if (!sv_isobject(obj)) { croak("Need an object as first argument"); } evaluator_destroy((void*)SvIV(SvRV(obj))); } __END__ =encoding utf8 =head1 NAME Math::Eval -- Evaluate Mathematic terms =head1 SYNOPSIS #!/usr/bin/perl use strict; use warnings; use Math::Eval; my $meval=Math::Eval->parse("7*x^9+5*x^3+11"); die("PARSE ERROR") unless($meval); print "f(x)=".$meval->get_string()."\n"; print "f($_)=".$meval->evaluate(x => $_)."\n" for(-10..10); my $meval2=$meval->derivative('x'); print "f'(x)=".$meval2->get_string()."\n"; print "f'($_)=".$meval2->evaluate(x => $_)."\n" for(-10..10); =head1 DESCRIPTION parse Mathematical String and evaluate the results =head1 AUTHOR ToPeG =head1 USING libmatheval Inline::C =head1 METHODS =over 4 =item parse($string) Create Math::Eval object from string containing mathematical representation of function. Math::Eval object could be used later to evaluate function for specific variable values or to calculate function derivative over some variable. String representation of function is allowed to consist of decimal numbers, constants, variables, elementary functions, unary and binary operations. Supported constants are (names that should be used are given in parenthesis): e (e), log2(e) (log2e), log10(e) (log10e), ln(2) (ln2), ln(10) (ln10), pi (pi), pi / 2 (pi_2), pi / 4 (pi_4), 1 / pi (1_pi), 2 / pi (2_pi), 2 / sqrt(pi) (2_sqrtpi), sqrt(2) (sqrt) and sqrt(1 / 2) (sqrt1_2). Variable name is any combination of alphanumericals and _ characters beginning with a non-digit that is not elementary function name. Supported elementary functions are (names that should be used are given in parenthesis): exponential (exp), logarithmic (log), square root (sqrt), sine (sin), cosine (cos), tangent (tan), cotangent (cot), secant (sec), cosecant (csc), inverse sine (asin), inverse cosine (acos), inverse tangent (atan), inverse cotangent (acot), inverse secant (asec), inverse cosecant (acsc), hyperbolic sine (sinh), cosine (cosh), hyperbolic tangent (tanh), hyperbolic cotangent (coth), hyperbolic secant (sech), hyperbolic cosecant (csch), hyperbolic inverse sine (asinh), hyperbolic inverse cosine (acosh), hyperbolic inverse tangent (atanh), hyperbolic inverse cotangent (acoth), hyperbolic inverse secant (asech), hyperbolic inverse cosecant (acsch), absolute value (abs), Heaviside step function (step) with value 1 defined for x = 0, Dirac delta function with infinity (delta) and not-a-number (nandelta) values defined for x = 0, and error function (erf). Supported unary operation is unary minus (’-’). Supported binary operations are addition (’+’), subtraction (’+’), multiplication (’*’), division multiplication (’/’) and exponentiation (’^’). Usual mathematical rules regarding operation precedence apply. Parenthesis (’(’ and ’)’) could be used to change priority order. =item get_variables( ) Return array of strings with names of variables appearing in function repre- sented by Math::Eval object =item get_string( ) Return textual representation (i.e. mathematical function) of Math::Eval object =item evaluate(var => $val, [ var => $val, ...]) Calculate value of function represented by Math::Eval object for given variable values. =item derivative($value) Create Math::Eval object for derivative of function represented by given Math::Eval object =back =cut =head1 BUGS see libmatheval =head1 TODO Errorhandling =head1 AUTHOR Tobias Grönhagen =head1 VERSION Version 1.0 17 Apr 2011 =head1 COPYRIGHT Copyright (c) Tobias Grönhagen. All rights reserved. =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms and conditions as Perl itself. This means that you can, at your option, redistribute it and/or modify it under either the terms the GNU Public License (GPL) version 2 or later, or under the Perl Artistic License. See http://dev.perl.org/licenses/ =head1 DISCLAIMER THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Use of this software in any way or in any form, source or binary, is not allowed in any country which prohibits disclaimers of any implied warranties of merchantability or fitness for a particular purpose or any disclaimers of a similar nature. IN NO EVENT SHALL I BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION (INCLUDING, BUT NOT LIMITED TO, LOST PROFITS) EVEN IF I HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE =cut