Search code examples
equationrakusolverequation-solving

solving an exponential equation in Raku


exponential equation

I'm trying to solve this exponential equation like this:

my ($l,$r);

for (1 .. 100) -> $x {
    $l = $x * e ** $x;
    $r = 5 * (e ** $x - 1);
    say $x if $l == $r;
    }

But it doesn't work. How to solve it in a straightforward and comprehensive fashion?


Solution

  • 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)'