When I ask Math::Symbolic::Derivative to take the partial derivative
of
A*(x - x_0)^2 + y_0 with respect to x_0,
and simplify, it returns the expression
(-2A*(x - x_0)^2)/(x - x_0)
When I do the same by hand, I get
-2A*(x - x_0)
The two are equivalent except when x == x_0. Then Symbolic expression
returns undef, while mine returns 0.
This is causing an error in Algorithm::CurveFit when fitting to a
parabola with the above formula, when the x-value of the initial guess
of the vertex is equal to one of the x-value data points submitted to
the curve fitting subroutine (x == x_0).
Please see the attached file for a test script that will reproduce the
error.
Running perl v5.8.8 built for i686-linux, using Math::Symbolic version
0.603, and Algorithm::CurveFit version 1.04. I also intend to submit
a bug under Algorithm::CurveFit so that they are aware of the issue
and the lack of handling of an undef return from deriv->value().
- John Refior
Subject: | math_sym_deriv_test.pl |
#!/usr/bin/perl
use strict;
use warnings;
use Test::More tests => 1;
use Math::Symbolic;
use Data::Dumper;
my $formula = 'A*(x-x_0)^2+y_0';
my $raw = Math::Symbolic::Operator->new( 'partial_derivative', $formula, 'x_0' );
my $deriv = $raw->simplify()->apply_derivatives()->simplify();
########################################################################
# When I do this partial derivative by hand, I get -2 * A * (x - x_0). #
# However, $deriv is now (-2A*(x - x_0)^2)/(x - x_0). #
# These are equivalent, except when x == x_0. Then mine by hand is 0, #
# and $deriv->value is undef. This is causing an error in #
# Algorithm::CurveFit for certain cases (when the x-value of the #
# initial guess of the vertex is equal to one of the x-data points #
# submitted) I've encountered when trying to perform curve fitting on #
# a parabola. #
print 'Simplified derivative expression is ', Dumper($deriv), "\n\n";
is( $deriv->value('x' => 2,
'A' => -5,
'x_0' => 2,
'y_0' => 20),
0,
'expect 0 when x=2');
print "Tests complete.\n";