solving an exponential equation in Raku
Sorry for the double-answering.
But here is a totally different much simpler approach solved in Raku.
(It probably can be formulated more elegant.)
#!/usr/bin/env raku
sub solver ($equ, $acc, $lower0, $upper0) {
my Real $lower = $lower0;
my Real $upper = $upper0;
my Real $middle = ($lower + $upper) / 2;
# zero must be in between
sign($equ($lower)) != sign($equ($upper)) || die 'Bad interval!';
for ^$acc { # accuracy steps
if sign($equ($lower)) != sign($equ($middle))
{ $upper = $middle }
else
{ $lower = $middle }
$middle = ($upper + $lower) / 2;
}
return $middle;
}
my $equ = -> $x { $x * e ** $x - 5 * (e ** $x - 1) }; # left side - right side
my $acc = 64; # 64 bit accuracy
my Real $lower = 1; # start search here
my Real $upper = 100; # end search here
my $solution = solver $equ, $acc, $lower, $upper;
say 'result is ', $solution;
say 'Inserted in equation calculates to ', $equ($solution), ' (hopefully nearly zero)'
For Perl 5 there is Math::GSL::Roots - Find roots of arbitrary 1-D functions
https://metacpan.org/pod/Math::GSL::Roots
Raku has support for using Perl 5 code or can access the GSL C library directly, can't it?
$fspec = sub {
my ( $x ) = shift;
# here the function has to be inserted in the format
# return leftside - rightside;
return ($x + $x**2) - 4;
};
gsl_root_fsolver_alloc($T); # where T is the solver algorithm, see link for the 6 type constants, e.g. $$gsl_root_fsolver_brent
gsl_root_fsolver_set( $s, $fspec, $x_lower, $x_upper ); # [$x_lower; $x_upper] is search interval
gsl_root_fsolver_iterate($s);
gsl_root_fsolver_iterate($s);
gsl_root_fsolver_iterate($s);
gsl_root_fsolver_iterate($s);
gsl_root_fsolver_iterate($s);
my $result = gsl_root_fsolver_root($s);
gsl_root_fsolver_free (s);
There are enhanced algorithms available (gsl_root_fdfsolver_*), if the derivative of a function is available.
See also https://www.gnu.org/software/gsl/doc/html/roots.html#examples for general usage