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