Maths Libraries

When I first started using Ruby I began with some mathematical projects, in particular a package for doing matrix arithmetic, which permits interactive entry of matrices. To make this work I needed to extend some standard Ruby methods, especially .to_s so that it could pretty-print matrices and complex numbers. These extensions are contained in the file mathext.rb below.

To use matrix.rb load it and then type, say, "A = matrix(2,3)", at the Ruby prompt, then enter each of the lines for a 2x3 matrix (which may contain all numeric types Ruby supports including complex and fractions/rationals) as you are prompted. You can perform arithmetic on these matrix variables, such as A + B, A+10, A*B and so on. Use the .>> method (as in "A.>>") to pretty-print the contents of a matrix, and follow it with a number (as in "A.>> 12") to alter the spacing of matrix columns.

Solver.rb contains a solver for sets of linear simultaneous equations which uses the matrix method. Again it has an interactive command-line interface which prompts you to enter variable names and then the correct number of equations. To use it simply type "solve" at the prompt.

Factorize.rb contains a routine for factorizing largish numbers far faster than the routine in mathext.rb - it employs a pre-computed lookup table of all the primes up to 9999999, which enables it to factorize many numbers of 20 digits or more, though for the worst cases with eight-digit or larger prime factors it will fail.

Surds.rb contains a Ruby class to implement irrational square roots of prime numbers as surds like √2, √3 and √5 and perform operations that yield surds as results. Every surd object has a method called simplify which reduces its value to the product of natural numbers and surds, so that for example surd(15).simplify returns √3√5. Using surds I define a function quadroot(a,b,c) that solves quadratic equations of the form ax²+bx+c=0 in terms of surds, so that for example quadroot(2,3,-1) returns the two roots:

-3 ± _/17 ---------- 4

Notice that because of Ruby's weird Unicode support I've had to bodge the square root sign using the ASCII characters _ and / even though there's a perfectly good root sign at Unicode 0x221A - I've been quite unable to get it to display (even in Shoes). Perhaps someone out there has a solution?

UPDATE HISTORY

mathext.rb version 3 fixes print formatting for Complex and Rational numbers so they don't sprout spaces in their middle.

matrix.rb version 3 introduces improved pretty-print tabulation, and shortened syntax to save typing on Android mobiles.