Euler's identity: Difference between revisions

new builtin
(Added Common Lisp version)
(new builtin)
Line 371:
 
=={{header|Phix}}==
<lang Phix>include builtins\complex.e -- (0.8.0+)
{{trans|Kotlin}}
complex res = complex_add(complex_exp(complex_mul(PI,I)),1)
Likewise Phix has no builtin complex number library, so this includes a minimal one.
?complex_sprint(res,both:=true)
<lang Phix>enum REAL,IMAG
?complex_sprint(complex_round(res,1e16),true)
type complex(object c)
?complex_sprint(complex_round(res,1e15))</lang>
return sequence(c) and length(c)=IMAG and atom(c[REAL]) and atom(c[IMAG])
end type
 
function iplus(complex a, b)
complex res = {a[REAL]+b[REAL],a[IMAG]+b[IMAG]}
return res
end function
 
function imul(complex a, b)
complex res = {a[REAL]*b[REAL]-a[IMAG]*b[IMAG],
a[REAL]*b[IMAG]+a[IMAG]*b[REAL]}
return res
end function
 
function iinv(complex c)
atom denom = c[REAL]*c[REAL]+c[IMAG]*c[IMAG]
complex res = {c[REAL]/denom,-c[IMAG]/denom}
return res
end function
 
function iunaryminus(complex c)
complex res = {-c[REAL],-c[IMAG]}
return res
end function
 
function iminus(complex a, b)
complex res = {a[REAL]-b[REAL],a[IMAG]-b[IMAG]}
return res
end function
 
function idiv(complex a, b)
complex res = imul(a,iinv(b))
return res
end function
function imodulus(complex a)
atom res = sqrt(a[REAL]*a[REAL]+a[IMAG]*a[IMAG])
return res
end function
 
function ifmt(complex c)
string res = substitute(sprintf("%g + %gi",c),"+ -","- ")
return res
end function
 
constant EPSILON = 1.0e-16
 
atom fact = 1, n = 2
complex x = {0,PI},
e = {1,PI},
pow = x,
e0
while 1 do
e0 = e
fact *= n
n += 1
pow = imul(pow,x)
e = iplus(e,idiv(pow,{fact,0}))
if imodulus(iminus(e,e0))<EPSILON then exit end if
end while
e = iplus(e,{1,0})
printf(1,"power(e,PI*i) + 1 = %s\n",{ifmt(e)})
-- round to 18 then 16 then 14 decimal places:
-- note that round() takes an inverted precision, and obviously I have
-- done things this way so you can see it /really is/ rounding to the
-- nearest 1e-18, 1e-16, and lastly 1e-14 in the output.
printf(1,"rounding:\n")
printf(1,"power(e,PI*i) + 1 = %s\n",{ifmt(sq_round(e,1000000000000000000))})
printf(1,"power(e,PI*i) + 1 = %s\n",{ifmt(sq_round(e,10000000000000000))})
printf(1,"power(e,PI*i) + 1 = %s\n",{ifmt(sq_round(e,100000000000000))})</lang>
{{out}}
The actual result and two rounded versions (to prove the rounding is doing what it should - the second arg is an inverted precision).
<pre>
"0+1.2246e-16i"
power(e,PI*i) + 1 = -8.88179e-16 - 9.71491e-17i
"0+1e-16i"
rounding:
"0"
power(e,PI*i) + 1 = -8.88e-16 - 9.7e-17i
power(e,PI*i) + 1 = -9e-16 - 1e-16i
power(e,PI*i) + 1 = 0 + 0i
</pre>
 
7,833

edits