Chebyshev coefficients: Difference between revisions

Added Wren
(Added Wren)
Line 1,639:
0.950 0.58168308946388 0.58168308946379 -8.992806E-014
1.000 0.54030230586814 0.54030230586859 4.468648E-013</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "/fmt" for Fmt
 
var mapRange = Fn.new { |x, min, max, minTo, maxTo| (x - min)/(max - min)*(maxTo - minTo) + minTo }
 
var chebCoeffs = Fn.new { |func, n, min, max|
var coeffs = List.filled(n, 0)
for (i in 0...n) {
var f = func.call(mapRange.call((Num.pi * (i + 0.5) / n).cos, -1, 1, min, max)) * 2 / n
for (j in 0...n) coeffs[j] = coeffs[j] + f * (Num.pi * j * (i + 0.5) / n).cos
}
return coeffs
}
 
var chebApprox = Fn.new { |x, n, min, max, coeffs|
if (n < 2 || coeffs.count < 2) Fiber.abort("'n' can't be less than 2.")
var a = 1
var b = mapRange.call(x, min, max, -1, 1)
var res = coeffs[0]/2 + coeffs[1]*b
var xx = 2 * b
var i = 2
while (i < n) {
var c = xx*b - a
res = res + coeffs[i]*c
a = b
b = c
i = i + 1
}
return res
}
 
var n = 10
var min = 0
var max = 1
var coeffs = chebCoeffs.call(Fn.new { |x| x.cos }, n, min, max)
System.print("Coefficients:")
for (coeff in coeffs) Fmt.print("$0s$1.15f", (coeff >= 0) ? " " : "", coeff)
System.print("\nApproximations:\n x func(x) approx diff")
for (i in 0..20) {
var x = mapRange.call(i, 0, 20, min, max)
var f = x.cos
var approx = chebApprox.call(x, n, min, max, coeffs)
var diff = approx - f
var diffStr = diff.toString
var e = diffStr[-4..-1]
diffStr = diffStr[0..-5]
diffStr = (diff >= 0) ? " " + diffStr[0..3] : diffStr[0..4]
Fmt.print("$1.3f $1.8f $1.8f $s", x, f, approx, diffStr + e)
}</lang>
 
{{out}}
<pre>
Coefficients:
1.64716947539031
-0.23229937161517
-0.05371511462205
0.00245823526698
0.00028211905743
-0.00000772222916
-0.00000058985565
0.00000001152143
0.00000000065963
-0.00000000001002
 
Approximations:
x func(x) approx diff
0.000 1.00000000 1.00000000 4.68e-13
0.050 0.99875026 0.99875026 -9.35e-14
0.100 0.99500417 0.99500417 4.61e-13
0.150 0.98877108 0.98877108 -4.72e-14
0.200 0.98006658 0.98006658 -4.60e-13
0.250 0.96891242 0.96891242 -2.31e-13
0.300 0.95533649 0.95533649 2.61e-13
0.350 0.93937271 0.93937271 4.61e-13
0.400 0.92106099 0.92106099 1.98e-13
0.450 0.90044710 0.90044710 -2.47e-13
0.500 0.87758256 0.87758256 -4.58e-13
0.550 0.85252452 0.85252452 -2.46e-13
0.600 0.82533561 0.82533561 1.95e-13
0.650 0.79608380 0.79608380 4.52e-13
0.700 0.76484219 0.76484219 2.54e-13
0.750 0.73168887 0.73168887 -2.27e-13
0.800 0.69670671 0.69670671 -4.47e-13
0.850 0.65998315 0.65998315 -4.37e-14
0.900 0.62160997 0.62160997 4.45e-13
0.950 0.58168309 0.58168309 -8.99e-14
1.000 0.54030231 0.54030231 4.47e-13
</pre>
 
=={{header|zkl}}==
9,476

edits