September 2017 Update
This commit is contained in:
parent
bba7bfd280
commit
ba8067c3b7
14570 changed files with 153136 additions and 63871 deletions
|
|
@ -0,0 +1,29 @@
|
|||
// version 1.1.2
|
||||
|
||||
class Rational(val num: Long, val den: Long) {
|
||||
override fun toString() = "$num/$den"
|
||||
}
|
||||
|
||||
fun decimalToRational(d: Double): Rational {
|
||||
val ds = d.toString().trimEnd('0').trimEnd('.')
|
||||
val index = ds.indexOf('.')
|
||||
if (index == -1) return Rational(ds.toLong(), 1L)
|
||||
var num = ds.replace(".", "").toLong()
|
||||
var den = 1L
|
||||
for (n in 1..(ds.length - index - 1)) den *= 10L
|
||||
while (num % 2L == 0L && den % 2L == 0L) {
|
||||
num /= 2L
|
||||
den /= 2L
|
||||
}
|
||||
while (num % 5L == 0L && den % 5L == 0L) {
|
||||
num /= 5L
|
||||
den /= 5L
|
||||
}
|
||||
return Rational(num, den)
|
||||
}
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
val decimals = doubleArrayOf(0.9054054, 0.518518, 2.405308, .75, 0.0, -0.64, 123.0, -14.6)
|
||||
for (decimal in decimals)
|
||||
println("${decimal.toString().padEnd(9)} = ${decimalToRational(decimal)}")
|
||||
}
|
||||
|
|
@ -50,8 +50,7 @@ test:
|
|||
Else
|
||||
tag='should be' soll
|
||||
say zin '=' fract tag
|
||||
-- Say left(zz/nn,60)
|
||||
Return
|
||||
Return
|
||||
|
||||
GCD: procedure
|
||||
/**********************************************************************
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
> [0.9054054, 0.518518, 0.75].each { |d| puts "%s %s" % [d, Rational(d).rationalize(0.0001)] }
|
||||
0.9054054 67/74
|
||||
0.518518 14/27
|
||||
0.75 3/4
|
||||
=> [0.9054054, 0.518518, 0.75]
|
||||
[0.9054054, 0.518518, 0.75].each { |f| puts "#{f} #{f.rationalize(0.0001)}" }
|
||||
# =>0.9054054 67/74
|
||||
# =>0.518518 14/27
|
||||
# =>0.75 3/4
|
||||
|
|
|
|||
|
|
@ -0,0 +1,14 @@
|
|||
fcn real2Rational(r,bound){
|
||||
if (r == 0.0) return(0,1);
|
||||
if (r < 0.0){
|
||||
result := real2Rational(-r, bound);
|
||||
return(-result[0],result[1]);
|
||||
} else {
|
||||
best,bestError := 1,(1.0).MAX;
|
||||
foreach i in ([1 .. bound + 1]){
|
||||
error := (r*i - (r*i).round()).abs();
|
||||
if (error < bestError) best,bestError = i,error;
|
||||
}
|
||||
return((r*best).round().toInt(),best);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
tests := T(0.750000000, 0.518518000, 0.905405400,
|
||||
0.142857143, 3.141592654, 2.718281828,
|
||||
-0.423310825, 31.415926536);
|
||||
foreach r in (tests) {
|
||||
print("%8.9f ".fmt(r));
|
||||
foreach i in (6)
|
||||
{ print(" %d/%d".fmt(real2Rational(r,(10).pow(i)).xplode())) }
|
||||
println();
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue