The stupid question is the question not asked PerlMonks

Symbolic mathematics in Perl

by tsee (Curate)
 on Aug 28, 2003 at 13:52 UTC Need Help??

```   1: # For some time now, symbolic calculation can be carried
2: # out from within Perl: (warning: plug from module author)
3: #
4: # If you find this interesting, check out the module on CPAN
5: # and/or actively help with the development!
6:
7: use strict;
8: use warnings;
9: use Math::Symbolic qw/:all/;
10:
11: my \$energy = parse_from_string(<<'HERE');
12: 	kinetic(mass, velocity, time) +
13: 	potential(mass, z, time)
14: HERE
15:
16: \$energy->implement(kinetic => '(1/2) * mass * velocity(time)^2');
17: \$energy->implement(potential => 'mass * g * z(t)');
18:
19: \$energy->set_value(g => 9.81); # permanently
20:
21: print "Energy is: \$energy\n";
22:
23: # Is how does the energy change with the height?
24: my \$derived = \$energy->new('partial_derivative', \$energy, 'z')
25:                      ->apply_derivatives()
26: 		     ->simplify();
27:
28: print "Changes with the heigth as: \$derived\n";
29:
30: # With whatever values you fancy:
31: print "Putting in some sample values: ",
32:       \$energy->value(mass => 20, velocity => 10, z => 5),
33:       "\n";
34:
35: # Too slow?
36: \$energy->implement(g => '9.81'); # To get rid of the variable
37:
38: my (\$sub) = Math::Symbolic::Compiler->compile(\$energy);
39:
40: print "This was much faster: ",
41:       \$sub->(20, 10, 5),  # vars ordered alphabetically
42:       "\n";
43:
44:
45: # Output:
46: # Energy is: (((1 / 2) * mass) * (velocity ^ 2)) + ((mass * g) * z)
47: # Changes with the heigth as: mass * g
48: # Putting in some sample values: 1981
49: # This was much faster: 1981
```

Replies are listed 'Best First'.
Re: Symbolic mathematics in Perl
by ambrus (Abbot) on Feb 27, 2004 at 21:06 UTC
Re: Symbolic mathematics in Perl
by tsee (Curate) on Aug 29, 2003 at 11:06 UTC
Sorry for replying to my own post, but I forgot to mention that interested parties are welcome to join the mailing lists and/or the developer team at http://sourceforge.net/projects/math-symbolic
That is interesting. Don't have much use for it, but it's cool nonetheless. :-D

Create A New User
Node Status?
node history
Node Type: perlcraft [id://287363]
Approved by valdez
Front-paged by grinder
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2017-12-14 05:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
What programming language do you hate the most?

Results (384 votes). Check out past polls.

Notices?