Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

matrix determinants

by ysth (Canon)
on Nov 17, 2003 at 03:30 UTC ( [id://307547]=sourcecode: print w/replies, xml ) Need Help??
Category: Miscellaneous
Author/Contact Info sthoenna@efn.org ysth
Description: A friend was reviewing precalculus (in preparation to return to school after a decade off and place into a real math class), and was working through some maxtrix determinant problems. I wrote this to help her catch arithmetic errors when calculating minors of a larger matrix. I only spent about 15 minutes, so its kind of rough, but I'm pretty satisfied, especially with how the input code handles errors.
#!/usr/bin/perl
use strict;
use warnings;

sub getmatrix {
    my $m = [];
    my $cols;
    rand()<.85 ? print "Enter matrix:\n" : print "tell me your matrix 
+and I'll tell you no lies:\n";
    while (!$cols || @$m != $cols) {
#    print "enter row:\n";
        my @row = split ' ', <>;
        if (@row < 2 || $cols && @row != $cols || grep /.\D|^[^\d-]/s,
+ @row) {
        print "try that row again:\n";
            @row = split ' ', <>;
            goto &getmatrix
                if @row < 2 || $cols && @row != $cols || grep /.\D|^[^
+\d-]/s, @row;
        }
        $cols ||= @row;
        push @$m, \@row;
    }
#    use Data::Dumper;
#    print Dumper $m;
    $m;
}

sub determine {
    my $m = shift;
    my $det = 0;
    if (@$m == 2) {
        $det = $m->[0][0] * $m->[1][1] - $m->[0][1] * $m->[1][0];
    } else {
        my @subm = map [@$_[1..$#$_]], @$m;
        for (0..$#$m) {
        if ($_ & 1) {
        $det -= $m->[$_][0] * determine([@subm[0..$_-1,$_+1..$#subm]])
+;
            } else {
                $det += $m->[$_][0] * determine([@subm[0..$_-1,$_+1..$
+#subm]]);
            }
        }
    }
    $det
}

while (1) {
    my $m = getmatrix();
    my $det = determine($m) || (rand()<.333 ? 0 : rand() < .5 ? 'zippo
+' : 'zilch');
    print "got: $det\n";
}
Replies are listed 'Best First'.
Re: matrix determinants
by Anonymous Monk on Nov 17, 2003 at 05:30 UTC
Re: matrix determinants
by etj (Priest) on Jun 26, 2022 at 00:55 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: sourcecode [id://307547]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2026-04-22 11:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.