Thread Math::Eval (5 answers)
Opened by topeg at 2011-04-17 15:31

topeg
 2011-04-17 15:31
#147812 #147812
User since
2006-07-10
2611 Artikel
BenutzerIn

user image
Ein kleines Modul zum parsen von Mathematischen Strings.
Es wird libmatheval dazu benutzt. Eingebunden mit CPAN:Inline::C
Das ist nichts großartiges. Es war nur eine Übung. Mir ging es hauptsächlich darum zu lernen Perl-Objekte in C richtig zu handhaben.

more (44.6kb):
Code (perl): (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
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 <matheval.h>

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 <osm@topeg.de>

=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

View full thread Math::Eval