Mathematical Ruby Scripts (mathn)

The mathn standard library, when combined with the core Math module, serves to make mathematical operations more pleasant in Ruby. The main purpose of mathn is to pull in other standard libraries and integrate them with the rest of Ruby’s numeric system. You’ll notice this right away when doing basic arithmetic:

>> 1 / 2
=> 0
>> Math.sqrt(-1)
Errno::EDOM: Numerical argument out of domain - sqrt ..

>> require "mathn"
=> true
>> 1 / 2
=> 1/2
>> 1 / 2  + 5 / 7
=> 17/14
>> Math.sqrt(-1)
=> (0+1i)

As you can see, integer division gives way when mathn is loaded, in favor of returning Rational objects. These behave like the fractions you learned in grade school, and keep values in exact terms rather than expressing them as floats where possible. Numbers also gracefully extend into the Complex field, without error. Although this sort of behavior might seem unnecessary for day-to-day programming needs, it can be very helpful for mathematical applications.

In addition to changing the way basic arithmetic works, mathn pulls in a few of the higher-level mathematical constructs. For those interested in enumerating prime numbers (for whatever fun reason you might have in mind), a class is provided. To give you a peek at how it works, we can do things like ask for the first 10 primes or how many primes exist up to certain numbers:

>> Prime.first(10)
=> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

>> Prime.find_index { |e| e > 1000 }
=> 168

In addition to enabling Prime, mathn ...

Get Ruby Best Practices now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.