Chebyshev coefficients: Difference between revisions

Add Swift
(Add Swift)
Line 1,264:
-1.0022591709e-11
</pre>
 
=={{header|Swift}}==
 
{{trans|Kotlin}}
 
<lang swift>import Foundation
 
typealias DFunc = (Double) -> Double
 
func mapRange(x: Double, min: Double, max: Double, minTo: Double, maxTo: Double) -> Double {
return (x - min) / (max - min) * (maxTo - minTo) + minTo
}
 
func chebCoeffs(fun: DFunc, n: Int, min: Double, max: Double) -> [Double] {
var res = [Double](repeating: 0, count: n)
 
for i in 0..<n {
let dI = Double(i)
let dN = Double(n)
let f = fun(mapRange(x: cos(.pi * (dI + 0.5) / dN), min: -1, max: 1, minTo: min, maxTo: max)) * 2.0 / dN
 
for j in 0..<n {
res[j] += f * cos(.pi * Double(j) * (dI + 0.5) / dN)
}
}
 
return res
}
 
func chebApprox(x: Double, n: Int, min: Double, max: Double, coeffs: [Double]) -> Double {
var a = 1.0
var b = mapRange(x: x, min: min, max: max, minTo: -1, maxTo: 1)
var res = coeffs[0] / 2.0 + coeffs[1] * b
let xx = 2 * b
var i = 2
 
while i < n {
let c = xx * b - a
res += coeffs[i] * c
(a, b) = (b, c)
i += 1
}
 
return res
}
 
let coeffs = chebCoeffs(fun: cos, n: 10, min: 0, max: 1)
 
print("Coefficients")
 
for coeff in coeffs {
print(String(format: "%+1.15g", coeff))
}
 
print("\nApproximations:\n x func(x) approx diff")
 
for i in stride(from: 0.0, through: 20, by: 1) {
let x = mapRange(x: i, min: 0, max: 20, minTo: 0, maxTo: 1)
let f = cos(x)
let approx = chebApprox(x: x, n: 10, min: 0, max: 1, coeffs: coeffs)
 
print(String(format: "%1.3f %1.8f %1.8f % 4.1e", x, f, approx, approx - f))
}</lang>
 
{{out}}
 
<pre>Coefficients
+1.64716947539031
-0.232299371615172
-0.0537151146220476
+0.00245823526698177
+0.000282119057434055
-7.72222915632059e-06
-5.89855645688475e-07
+1.15214277562892e-08
+6.59630204624673e-10
-1.0021858343201e-11
 
Approximations:
x func(x) approx diff
0.000 1.00000000 1.00000000 4.7e-13
0.050 0.99875026 0.99875026 -9.3e-14
0.100 0.99500417 0.99500417 4.6e-13
0.150 0.98877108 0.98877108 -4.7e-14
0.200 0.98006658 0.98006658 -4.6e-13
0.250 0.96891242 0.96891242 -2.3e-13
0.300 0.95533649 0.95533649 2.6e-13
0.350 0.93937271 0.93937271 4.6e-13
0.400 0.92106099 0.92106099 2.0e-13
0.450 0.90044710 0.90044710 -2.5e-13
0.500 0.87758256 0.87758256 -4.6e-13
0.550 0.85252452 0.85252452 -2.5e-13
0.600 0.82533561 0.82533561 2.0e-13
0.650 0.79608380 0.79608380 4.5e-13
0.700 0.76484219 0.76484219 2.5e-13
0.750 0.73168887 0.73168887 -2.3e-13
0.800 0.69670671 0.69670671 -4.5e-13
0.850 0.65998315 0.65998315 -4.4e-14
0.900 0.62160997 0.62160997 4.5e-13
0.950 0.58168309 0.58168309 -9.0e-14
1.000 0.54030231 0.54030231 4.5e-13</pre>
 
=={{header|VBScript}}==