100% , .. (numerator, denominator), , , ..
.
Double, . ,
let x : Double = 7/10
x 0.7,
a Double.
print(String(format:"%a", x)) // 0x1.6666666666666p-1
, x
0x16666666666666 * 2^(-53) = 6305039478318694 / 9007199254740992
≈ 0.69999999999999995559107901499373838305
, x
6305039478318694 / 9007199254740992, , , ,
. , , 7/10, :
let x : Double = 69999999999999996/100000000000000000
x,
0.7 Double.
, x 7/10 69999999999999996/100000000000000000?
, .
, Double
.
( LCM Swift.)
( ) h n/k n, x,
Swift:
typealias Rational = (num : Int, den : Int)
func rationalApproximationOf(x0 : Double, withPrecision eps : Double = 1.0E-6) -> Rational {
var x = x0
var a = floor(x)
var (h1, k1, h, k) = (1, 0, Int(a), 1)
while x - a > eps * Double(k) * Double(k) {
x = 1.0/(x - a)
a = floor(x)
(h1, k1, h, k) = (h, k, h1 + Int(a) * h, k1 + Int(a) * k)
}
return (h, k)
}
:
rationalApproximationOf(0.333333)
rationalApproximationOf(0.25)
rationalApproximationOf(0.1764705882)
- 1.0E-6, :
rationalApproximationOf(0.142857)
rationalApproximationOf(0.142857, withPrecision: 1.0E-10)
rationalApproximationOf(M_PI)
rationalApproximationOf(M_PI, withPrecision: 1.0E-7)
rationalApproximationOf(M_PI, withPrecision: 1.0E-10)
Swift 3:
typealias Rational = (num : Int, den : Int)
func rationalApproximation(of x0 : Double, withPrecision eps : Double = 1.0E-6) -> Rational {
var x = x0
var a = x.rounded(.down)
var (h1, k1, h, k) = (1, 0, Int(a), 1)
while x - a > eps * Double(k) * Double(k) {
x = 1.0/(x - a)
a = x.rounded(.down)
(h1, k1, h, k) = (h, k, h1 + Int(a) * h, k1 + Int(a) * k)
}
return (h, k)
}
:
rationalApproximation(of: 0.333333)
rationalApproximation(of: 0.142857, withPrecision: 1.0E-10)