-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFraction.sc
executable file
·75 lines (50 loc) · 1.33 KB
/
Fraction.sc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
a = Fraction(5, 10);
a.numer;
a.denom;
b = Fraction(3, 5);
a + b
*/
Fraction {
var <>numer, <>denom;
*new { arg numerator, denominator;
^super.new.initFraction(numerator, denominator);
}
initFraction { arg thisNumerator, thisDenominator;
var factor;
(thisDenominator == 0).if(
{// if denominator=0, both are 0
this.numer_(0);
this.denom_(0);
}, {
factor = gcd(thisNumerator.abs.asInteger, thisDenominator.abs.asInteger);
(thisDenominator < 0).if({factor = factor.neg});
this.numer_((thisNumerator/factor).abs);
this.denom_((thisDenominator/factor).abs);
})
}
+ { arg other;
^Fraction(
(this.numer * other.denom) + (this.denom * other.numer),
this.denom * other.denom
)
}
- { arg other;
^Fraction(
(this.numer * other.denom) - (this.denom * other.numer),
this.denom * other.denom
)
}
* { arg other;
^Fraction(
this.numer * other.numer,
this.denom * other.denom
)
}
/ { arg other;
^Fraction(
this.numer * other.denom,
this.denom * other.numer
)
}
}