Formal power series: Difference between revisions

(J draft)
Line 923:
SIN(x) = x-0.16666666666666666x3+0.008333333333333333x5-1.984126984126984E-4x7+2.7557319223985893E-6x9-2.505210838544172E-8x11+...
COS(x) = 1.0-0.5x2+0.041666666666666664x4-0.001388888888888889x6+2.48015873015873E-5x8-2.7557319223985894E-7x10+...
 
=={{header|Lua}}==
Parts of this depend on the formula for integration of a power series: integral(sum(a_n x^n)) = sum(a_n / n * x(n+1))
 
<lang lua>powerseries = setmetatable({
__add = function(z1, z2) return powerseries(function(n) return z1.coeff(n) + z2.coeff(n) end) end,
__sub = function(z1, z2) return powerseries(function(n) return z1.coeff(n) - z2.coeff(n) end) end,
__mul = function(z1, z2) return powerseries(function(n)
local ret = 0
for i = 0, n do
ret = ret + z1.coeff(i) * z2.coeff(n-i)
end
return ret
end) end,
__div = function(z1, z2) return powerseries(function(n)
local ret = 0
for i = 0, n do
for j = 0, n - i do
ret = ret + z1.coeff(i) * z2.coeff(j) * z2.coeff(n-i-j)
end
end
return ret / z2.coeff(0)^(n+1)
end) end,
__pow = function(z1, p) -- for a series z, z^n returns the nth derivative of z. negative values take integrals.
if p == 0 then return z1 end
elseif p > 0 then return powerseries(function(i) return z1.coeff(i+1)*(i+1) end)^(p-1) -- return the p-1th derivative of the derivative
else return powerseries(function(i) return z1.coeff(i-1)/i end)^(p+1) --similar to above
end
end,
__unm = function(z1) return powerseries(function(n) return -z1.coeff(n) end) end,
__index = function(z, n) return z.coeff(n) end}
}, {__call = function(z, f) return setmetatable({coeff = f}, z) end})
 
cosine = powerseries(function(n)
if(n == 0) then return 1
else return -((sine^(-1))[n]) --defer to the integral of sine function
end
end)
 
sine = powerseries(function(n)
if(n == 0) then return 0
else return (cosine^(-1))[n] --defer to the integral of cosine function
end
end)
 
print(sine[1], sine[3], sine[5], sine[7], cosine[0], cosine[2], cosine[4], cosine[6])</lang>
 
=={{header|Python}}==
Anonymous user