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