-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExtendedFraction.java
89 lines (81 loc) · 2.09 KB
/
ExtendedFraction.java
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package siteswapsuite;
public class ExtendedFraction {
private ExtendedInteger numerator;
private int denominator;
private int sign;
private static int gcm(int a, int b) {
return b == 0 ? a : gcm(b, a % b);
}
public ExtendedFraction(ExtendedInteger top, int bottom) {
if(bottom != 0) {
//extract sign
if(top.sign() == 0)
this.sign = 0;
else {
if(top.sign() < 0 && bottom < 0 || top.sign() > 0 && bottom > 0)
this.sign = 1;
else {
this.sign = -1;
}
}
//take abs of top and bottom
bottom = Math.abs(bottom);
if(top.sign() < 0)
top.negate();
//reduce common factors
if(!top.isInfinite()) {
int gcm = gcm(top.finiteValue(), bottom);
this.numerator = new ExtendedInteger(top.finiteValue()/gcm);
this.denominator = bottom/gcm;
} else {
this.denominator = bottom;
this.numerator = top;
}
} else {
this.denominator = 0;
this.numerator = top;
}
}
public ExtendedInteger numerator() {
return this.numerator;
}
public int denominator() {
return this.denominator;
}
public Float floatValue() {
if(this.denominator == 0)
return Float.NaN;
if(this.numerator.isInfinite()) {
if(this.sign < 0)
return Float.NEGATIVE_INFINITY;
else
return Float.POSITIVE_INFINITY;
} else {
return ((Integer)this.numerator.finiteValue()).floatValue()/((Integer)this.denominator).floatValue();
}
}
public String toString() {
if(this.denominator == 0)
return "NaN";
if(this.numerator.isInfinite()) {
if(this.sign < 0)
return (new ExtendedInteger(InfinityType.NEGATIVE_INFINITY)).toString();
else
return (new ExtendedInteger(InfinityType.POSITIVE_INFINITY)).toString();
} else {
if(this.sign == 0)
return "0";
else {
if(this.denominator == 1) {
if(this.sign < 0)
return "-" + this.numerator.toString();
return this.numerator.toString();
} else {
if(this.sign < 0)
return "-" + this.numerator.toString() + "/" + ((Integer)this.denominator).toString();
return this.numerator.toString() + "/" + ((Integer)this.denominator).toString();
}
}
}
}
}