Browse | Submit A New Snippet | Create A Package

## Surds

Type:
Class
Category:
Math Functions
Language:
Ruby

Description:
Adds a new class Surd to Ruby, which permits arithmetic using irrational roots like √2 and √3. Also provides a function to find the roots of a quadratic equation in terms of surds, rather than floats.

### Versions Of This Snippet::

Dick Pountain
 Snippet ID Download Version Date Posted Author Delete 551 1.8 2009-12-31 19:59 Dick Pountain

## Latest Snippet Version: :1.8

```#---------------------------------------------------
# Class of irrational squareroot objects
#---------------------------------------------------

require "..\\mathext.rb"
require "ffactorize.rb"

class Surd
attr_accessor :v

def initialize(value)
@v=value
end

def to_s
s = (sprintf "%c",  95)         # fudge squareroot symbol using _/
s = s+(sprintf "%c",  47)
if @v > 1 then
r=s+@v.to_s
elsif @v == 1 then
r="1"
elsif @v == 0 then
r ="0"
elsif @v == -1 then
r = "i"
elsif @v < -1 then
z=-@v
r=s+z.to_s+"i"
return r
end
end

def to_f
csqrt(@v)                              # my own complex squareroot function from mathext.rb
end

def *(s)
Surd.new( self.v *  s.v)       # multipy by another surd; doesn't simplify product, call simplify on result
end

# --------------------------------------------------------------------------------------------------------------
#  simplify: express @v as A product of natural numbers and prime surds
#---------------------------------------------------------------------------------------------------------------
def __countfactors(f)
factors=f.uniq
facs = {}
factors.each{|i| facs[i] = 0}
f.each{|i| facs[i] += 1}
return facs
end

def __rootfactors(num, count)
prod=1;   sr = ""
# how many repeated factors?
(count/2).times {prod *= num}
# is there a surd left over?
sr = Surd.new(num) if count % 2 == 1
return [prod, sr]
end

def simplify
n=1; s=[]; out = []
if @v==0 or @v==1 then
out << @v
else
allfacs = ffactorize(@v)
unfacs = allfacs.uniq
cfacs = __countfactors allfacs
#DEBUG p cfacs
unfacs.each do |i|
x = __rootfactors(i, cfacs[i])
n *= x[0]
s << x[1]
end
out << n   if n > 1
out << s
out << Surd.new(-1)  if @v < 0
end
return out
end

end # Class Surd

# Shorthand function for declaring surd literals
def surd(n)
Surd.new(n)
end

# Constant, squareroot of minus one
i_ = surd(-1)

#----------------------------------------------------------------------------------------------
# Find roots of quadratic equation ax²+bx+c=0 in terms of surds
# (doesn't simplify if roots are integers)
#----------------------------------------------------------------------------------------------
z=surd(b*b-4*a*c).simplify
pm=sprintf "%c", 177
r = "\n"+ (-b).to_s+" #{pm} " + z.to_s + "\n"
# calculate length of bar between num and denom
x=r.length
r += ("_" * x)+"\n"+ (" " * (x/2)) + (2*a).to_s
end