Hi guys! I have been working on a fraction class for a while. The usage is documented inside the project.
-- My fraction class
function setup()
-- Usage of the fraction class
half = fraction(1, 2) -- Traditional syntax, works well with all fractions, including decimals
third = fraction(1, 3)
quarter = fraction(1 / 4) -- Alternative syntax, does not work for fractions such as 1/3
fifth = fraction(.2) -- note how the denominator defaults to 1
pi = fraction(355,113)
print("Half =", half)
print("Third =", third, "which in decimal is =", third.value)
print("Two Quarters =", quarter * 2)
print("Half a fifth =", half * fifth)
print("Fifth =", fifth)
print("A Third plus a half =", third + half )
print("A half minus a third =", half - third)
print("One and a half =", half + 1)
print("Half minus one =", half - 1)
print("Half didvided by a third =", half/third)
print("Half to the power of 3 =", half ^ 3)
print("Half to the power of minus 3 =", half ^ -3)
print("Negative half =", -half)
print("My fraction approximation of Pi =", pi.value, "and Codea/Luas approximation =", math.pi)
print("Enjoy!")
end
fraction = class()
function math.hcf(n, d)
while not (d == 0) do
n, d = d, n % d
end
return n
end
function fraction:init(n, d)
self.n = n
self.d = d or 1
self:_set()
self.value = self.n / self.d
end
function fraction:_set()
if not (self.n % 1 == 0) then
local zeros = 0
local rem = .5
while not (rem % 1 == 0) do
zeros = zeros + 1
rem = self.n * (10 ^ zeros)
end
self.n = rem
self.d = self.d * (10 ^ zeros)
end
if not (self.d % 1 == 0) then
local zeros = 0
local rem = 0.5
while not (rem % 1 == 0) do
zeros = zeros + 1
rem = self.d * (10 ^ zeros)
end
self.n = self.n * (10 ^ zeros)
self.d = rem
end
local gcd = math.hcf(self.n, self.d)
self.n = self.n / gcd
self.d = self.d / gcd
end
function fraction:__add(t)
if type(t) == "number" then
return fraction(self.n + self.d * t, self.d)
elseif type(t) == "table" and t.n and t.d then
return fraction(self.n * t.d + t.n * self.d, self.d * t.d)
end
end
function fraction:__sub(t)
if type(t) == "number" then
return fraction(self.n - self.d * t, self.d)
elseif type(t) == "table" and t.n and t.d then
return fraction(self.n * t.d - t.n * self.d, self.d * t.d)
end
end
function fraction:__mul(t)
if type(t) == "number" then
return fraction(self.n * t, self.d)
elseif type(t) == "table" and t.n and t.d then
return fraction(self.n * t.n, self.d * t.d)
end
end
function fraction:__div(t)
if type(t) == "number" then
return fraction(self.n, self.d * t)
elseif type(t) == "table" and t.n and t.d then
return fraction(self.n * t.d, self.d * t.n)
end
end
function fraction:__unm()
return fraction(-self.n, self.d)
end
function fraction:__pow(exp)
local n = fraction(1)
if exp > 0 then
for i = 1, exp do
n = n * fraction(self.n, self.d)
end
elseif exp < 0 then
for i = -1, exp, -1 do
n = n / fraction(self.n, self.d)
end
end
return n
end
function fraction:__tostring()
return self.n.."/"..self.d
end
Thanks!