Formal power series: Difference between revisions

m (→‎{{header|Tcl}}: added zkl header)
Line 2,251:
 
=={{header|zkl}}==
<lang zkl>class IPS{
var [protected] w; // the coefficients of the infinite series
fcn init(w_or_a,b,c,etc){ // IPS(1,2,3) --> (1,2,3,0,0,...)
switch [arglist]{
case(Walker) { w=w_or_a.tweak(Void,0) }
else { w=vm.arglist.walker().tweak(Void,0) }
}
}
fcn __opAdd(ipf){ //IPS(1,2,3)+IPS(4,5)-->IPS(5,6,3,0,...), returns modified self
switch[arglist]{
case(1){ addConst(ipf) } // IPS + int/float
else { w=w.zipWith('+,ipf.w) } // IPS + IPS
}
self
}
fcn __opSub(ipf){ w=w.zipWith('-,ipf.w); self } // IPS - IPS
fcn __opMul(ipf){ } // stub
fcn __opDiv(x){ w.next().toFloat()/x } // *IPS/x, for integtate()
fcn __opNegate { w=w.tweak(Op("--")); self }
// integtate: b0 = 0 by convention, bn = an-1/n
fcn integrate{ w=w.zipWith('/,[1..]).push(0.0); self }
fcn diff { w=w.zipWith('*,[1..]); self }
fcn facts{ (1).walker(*).tweak(fcn(n){ (1).reduce(n,'*,1) }) } // 1!,2!...
fcn walk(n){ w.walk(n) }
fcn value(x,N=15){ ns:=[1..]; w.reduce(N,'wrap(s,an){ s + an*x.pow(ns.next()) }) }
fcn cons(k){ w.push(k); self } //--> k, a0, a1, a2, ...
// addConst(k) --> k + a0, a1, a2, ..., same as k + IPS
fcn addConst(k){ (w.next() + k) : w.push(_); self }
}</lang>
Add two power series. Add a const to get: 11 - (1 + 2x + 3x^2) ...
<lang zkl>(IPS(1,2,3) + IPS(4,5)).walk(5).println();
(-IPS([1..]) + 11).walk(5).println();</lang>
{{out}}
<pre>
L(5,7,3,0,0)
L(10,-2,-3,-4,-5)
</pre>
Define sine in terms of a Taylor series, cos in terms of sine.
<lang zkl>fcn sine{ // sine Taylor series: x - x^3/3! + x^5/5! - x^7/7! + x^9/9! - ...
IPS(Utils.Helpers.cycle(1.0, 0.0, -1.0, 0.0).zipWith('/,IPS.facts()))
.cons(0.0)
}
print("Sine Taylor series: "); dostuff(sine,"sin");
 
fcn cosine{ -sine().integrate() + 1.0 }
print("Cosine power series: "); dostuff(cosine,"cos");
 
fcn dostuff(ips,name){ // print series, evaluate at various points
f:='wrap(x,xnm){ v:=ips().value(x);
println("%s(%s) \U2192; %f \U394;=%f".fmt(name,xnm,v,x.Method(name)()-v));
};
ips().walk(15).println();
f(0.0,"0"); f((1.0).pi/4,"\Ubc;\U3c0;");
f((1.0).pi/2,"\Ubd;\U3c0;"); f((1.0).pi,"\U3c0;");
}</lang>
{{out}}
<pre>
Sine Taylor series: L(0,1,0,-0.166667,0,0.00833333,0,-0.000198413,0,2.75573e-06,0,-2.50521e-08,0,1.6059e-10,0)
sin(0) → 0.000000 Δ=0.000000
sin(¼π) → 0.707107 Δ=-0.000000
sin(½π) → 1.000000 Δ=-0.000000
sin(π) → 0.000021 Δ=-0.000021
Cosine power series: L(1,0,-0.5,0,0.0416667,0,-0.00138889,0,2.48016e-05,0,-2.75573e-07,0,2.08768e-09,0,-1.14707e-11)
cos(0) → 1.000000 Δ=0.000000
cos(¼π) → 0.707107 Δ=0.000000
cos(½π) → -0.000000 Δ=0.000000
cos(π) → -1.000004 Δ=0.000004
</pre>
Anonymous user