Euler's identity: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎{{header|Wren}}: Removed leading and trailing white space.)
m (→‎{{header|Wren}}: Minor tidy)
 
(32 intermediate revisions by 19 users not shown)
Line 3: Line 3:




In mathematics,   ''Euler's identity''   (also known as   ''Euler's equation'')   is the equality:
In mathematics, ''Euler's identity'' is the equality:


<span style="font-size:150%;font-style:bold;"><span style="font-style:italic">e<sup>i<math>\pi</math></sup></span> + 1 = 0</span>
<span style="font-size:150%;font-style:bold;"><span style="font-style:italic">e<sup>i<math>\pi</math></sup></span> + 1 = 0</span>
Line 27: Line 27:


If that is the case, or there is some other limitation, show
If that is the case, or there is some other limitation, show
that &nbsp; <big>e<sup>i<math>\pi</math></sup> + 1</big> &nbsp; is ''approximately'' equal to zero and
that <big>e<sup>i<math>\pi</math></sup> + 1</big> is ''approximately'' equal to zero and
show the amount of error in the calculation.
show the amount of error in the calculation.


If your language is capable of symbolic calculations, show
If your language is capable of symbolic calculations, show
that &nbsp; <big>e<sup>i<math>\pi</math></sup> + 1</big> &nbsp; is ''exactly'' equal to zero for bonus kudos points.
that <big>e<sup>i<math>\pi</math></sup> + 1</big> is ''exactly'' equal to zero for bonus kudos points.
<br><br>
<br><br>


Line 37: Line 37:
{{trans|Python}}
{{trans|Python}}


<lang 11l>print(math:e ^ (math:pi * 1i) + 1)</lang>
<syntaxhighlight lang="11l">print(math:e ^ (math:pi * 1i) + 1)</syntaxhighlight>


{{out}}
{{out}}
Line 43: Line 43:
1.22465e-16i
1.22465e-16i
</pre>
</pre>

=={{header|Ada}}==
<syntaxhighlight lang="ada">with Ada.Long_Complex_Text_IO; use Ada.Long_Complex_Text_IO;
with Ada.Numerics; use Ada.Numerics;
with Ada.Numerics.Long_Complex_Types; use Ada.Numerics.Long_Complex_Types;
with Ada.Numerics.Long_Complex_Elementary_Functions; use Ada.Numerics.Long_Complex_Elementary_Functions;
procedure Eulers_Identity is
begin
Put (Exp (Pi * i) + 1.0);
end Eulers_Identity;</syntaxhighlight>

{{out}}
<pre>( 0.00000000000000E+00, 1.22464679914735E-16)</pre>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 48: Line 61:
<br>
<br>
We could use the identity exp(x + iy) = exp(x)( cos y + i sin y ), however the following uses a series expansion for exp(ix).
We could use the identity exp(x + iy) = exp(x)( cos y + i sin y ), however the following uses a series expansion for exp(ix).
<lang algol68>BEGIN
<syntaxhighlight lang="algol68">BEGIN
# calculate an approximation to e^(i pi) + 1 which should be 0 (Euler's identity) #
# calculate an approximation to e^(i pi) + 1 which should be 0 (Euler's identity) #


Line 100: Line 113:
)
)
)
)
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
e^(i*pi) + 1 ~ 0.00000000000000000307 -0.00000000000000002926i
e^(i*pi) + 1 ~ 0.00000000000000000307 -0.00000000000000002926i
</pre>
</pre>

=={{header|Bracmat}}==
<syntaxhighlight lang="bracmat">e^(i*pi)+1</syntaxhighlight>By symbolic calculation:<pre>0</pre>


=={{header|C}}==
=={{header|C}}==
Line 110: Line 126:


The following code has been tested with gcc 5.4.0 on Ubuntu 16.04.
The following code has been tested with gcc 5.4.0 on Ubuntu 16.04.
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <math.h>
#include <math.h>
#include <complex.h>
#include <complex.h>
Line 123: Line 139:
printf("e ^ %lci + 1 = [%.16f, %.16f] %lc 0\n", pi, creal(e), cimag(e), ae);
printf("e ^ %lci + 1 = [%.16f, %.16f] %lc 0\n", pi, creal(e), cimag(e), ae);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{output}}
{{output}}
Line 130: Line 146:
</pre>
</pre>


=={{header|C sharp}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Numerics;
using System.Numerics;


Line 142: Line 158:
Console.WriteLine(Complex.Pow(e, i * π) + 1);
Console.WriteLine(Complex.Pow(e, i * π) + 1);
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 149: Line 165:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <complex>
#include <complex>


Line 155: Line 171:
std::cout << std::exp(std::complex<double>(0.0, M_PI)) + 1.0 << std::endl;
std::cout << std::exp(std::complex<double>(0.0, M_PI)) + 1.0 << std::endl;
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{output}}
{{output}}
Line 165: Line 181:
=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Common Lisp has complex number arithmetic built into it.
Common Lisp has complex number arithmetic built into it.
<syntaxhighlight lang="common lisp">
<lang Common Lisp>
(+ 1 (exp (complex 0 pi)))
(+ 1 (exp (complex 0 pi)))
</syntaxhighlight>
</lang>
<pre>
<pre>
#C(0.0L0 -5.0165576136843360246L-20)
#C(0.0L0 -5.0165576136843360246L-20)
</pre>
</pre>
=={{header|Delphi}}==
{{libheader| System.VarCmplx}}
<syntaxhighlight lang="delphi">
program Euler_identity;


{$APPTYPE CONSOLE}

uses
System.VarCmplx;

begin
var result := VarComplexExp(Pi * VarComplexCreate(0, 1)) + 1;
writeln(result);
readln;
end.</syntaxhighlight>
{{out}}
<pre>0 + 0i</pre>

=={{header|F_Sharp|F#}}==
As per the discussion page this task as described is to show that -1+1=0
<syntaxhighlight lang="fsharp">
printfn "-1 + 1 = %d" (-1+1)
</syntaxhighlight>
{{out}}
<pre>
-1 + 1 = 0
</pre>
I shall also show that cos π = -1 and sin π = 0
<syntaxhighlight lang="fsharp">
printfn "cos(pi)=%f and sin(pi)=%f" (cos 3.141592653589793) (sin 3.141592653589793)
</syntaxhighlight>
{{out}}
<pre>
cos(pi)=-1.000000 and sin(pi)=0.000000
</pre>
I shall try the formula e<sup>iπ</sup>. I'll use the MathNet.Numerics package. I'll leave you the reader to determine what it 'proves'.
<syntaxhighlight lang="fsharp">
let i =MathNet.Numerics.complex(0.0,1.0);;
let pi=MathNet.Numerics.complex(MathNet.Numerics.Constants.Pi,0.0);;
let e =MathNet.Numerics.complex(MathNet.Numerics.Constants.E ,0.0);;
printfn "e**(i*pi) = %A" (e**(i*pi));;
</syntaxhighlight>
{{out}}
<pre>
e**(i*pi) = (-1, 1.2246467991473532E-16)
</pre>
=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: math math.constants math.functions prettyprint ;
<syntaxhighlight lang="factor">USING: math math.constants math.functions prettyprint ;
1 e pi C{ 0 1 } * ^ + .</lang>
1 e pi C{ 0 1 } * ^ + .</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
C{ 0.0 1.224646799147353e-016 }
C{ 0.0 1.224646799147353e-016 }
</pre>
</pre>

=={{header|Forth}}==
Uses fs. (scientific) to print the imaginary term, since that's the one that's inexact.
<syntaxhighlight lang="forth">
." e^(i*π) + 1 = " pi fcos 1e0 f+ f. '+ emit space pi fsin fs. 'i emit cr
bye
</syntaxhighlight>
{{Out}}
<pre>
e^(i*π) + 1 = 0. + 1.22464679914735E-16 i
</pre>

=={{header|Fortran}}==
<syntaxhighlight lang="fortran">
program euler
use iso_fortran_env, only: output_unit, REAL64
implicit none

integer, parameter :: d=REAL64
real(kind=d), parameter :: e=exp(1._d), pi=4._d*atan(1._d)
complex(kind=d), parameter :: i=(0._d,1._d)

write(output_unit,*) e**(pi*i) + 1
end program euler
</syntaxhighlight>
{{out}}
<pre>
(0.0000000000000000,2.89542045005908316E-016)
</pre>

=={{header|FreeBASIC}}==

Provides complex arithmetic and a very rapidly converging algorithm for e^z.

<syntaxhighlight lang="freebasic">#define PI 3.141592653589793238462643383279502884197169399375105821
#define MAXITER 12

'---------------------------------------
' complex numbers and their arithmetic
'---------------------------------------

type complex
r as double
i as double
end type

function conj( a as complex ) as complex
dim as complex c
c.r = a.r
c.i = -a.i
return c
end function

operator + ( a as complex, b as complex ) as complex
dim as complex c
c.r = a.r + b.r
c.i = a.i + b.i
return c
end operator

operator - ( a as complex, b as complex ) as complex
dim as complex c
c.r = a.r - b.r
c.i = a.i - b.i
return c
end operator

operator * ( a as complex, b as complex ) as complex
dim as complex c
c.r = a.r*b.r - a.i*b.i
c.i = a.i*b.r + a.r*b.i
return c
end operator

operator / ( a as complex, b as complex ) as complex
dim as double bcb = (b*conj(b)).r
dim as complex acb = a*conj(b), c
c.r = acb.r/bcb
c.i = acb.i/bcb
return c
end operator

sub printc( a as complex )
if a.i>=0 then
print using "############.############### + ############.############### i"; a.r; a.i
else
print using "############.############### - ############.############### i"; a.r; -a.i
end if
end sub

function intc( n as integer ) as complex
dim as complex c
c.r = n
c.i = 0.0
return c
end function

function absc( a as complex ) as double
return sqr( (a*conj(a)).r )
end function

'-----------------------
' the algorithm
' Uses a rapidly converging continued
' fraction expansion for e^z and recursive
' expressions for its convergents
'-----------------------

dim as complex pii, pii2, curr, A2, A1, A0, B2, B1, B0
dim as complex ONE, TWO
dim as integer i, k = 2
pii.r = 0.0
pii.i = PI
pii2 = pii*pii

B0 = intc(2)
A0 = intc(2)
B1 = (intc(2) - pii)
A1 = B0*B1 + intc(2)*pii
printc( A0/B0)
print " Absolute error = ", absc(A0/B0)
printc( A1/B1)
print " Absolute error = ", absc(A1/B1)

for i = 1 to MAXITER
k = k + 4
A2 = intc(k)*A1 + pii2*A0
B2 = intc(k)*B1 + pii2*B0
curr = A2/B2
A0 = A1
A1 = A2
B0 = B1
B1 = B2
printc( curr )
print " Absolute error = ", absc(curr)
next i</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main
import (
import (
Line 191: Line 388:
func main() {
func main() {
fmt.Println(cmplx.Exp(math.Pi * 1i) + 1.0)
fmt.Println(cmplx.Exp(math.Pi * 1i) + 1.0)
}</lang>
}</syntaxhighlight>


{{output}}
{{output}}
Line 201: Line 398:
=={{header|Groovy}}==
=={{header|Groovy}}==
Because the Groovy language does not provide a built-in facility for complex arithmetic, this example relies on the Complex class defined in the [[Complex_numbers#Groovy|Complex numbers]] example.
Because the Groovy language does not provide a built-in facility for complex arithmetic, this example relies on the Complex class defined in the [[Complex_numbers#Groovy|Complex numbers]] example.
<lang groovy>import static Complex.*
<syntaxhighlight lang="groovy">import static Complex.*


Number.metaClass.mixin ComplexCategory
Number.metaClass.mixin ComplexCategory
Line 210: Line 407:
println "e ** (π * i) + 1 = " + (e ** (π * i) + 1)
println "e ** (π * i) + 1 = " + (e ** (π * i) + 1)


println "| e ** (π * i) + 1 | = " + (e ** (π * i) + 1).ρ</lang>
println "| e ** (π * i) + 1 | = " + (e ** (π * i) + 1).ρ</syntaxhighlight>
Output: (yadda, yadda, dust, yadda)
Output: (yadda, yadda, dust, yadda)
<pre>e ** (π * i) + 1 = 1.2246467991473532E-16i
<pre>e ** (π * i) + 1 = 1.2246467991473532E-16i
Line 218: Line 415:


A double is not quite real.
A double is not quite real.
<lang Haskell>import Data.Complex
<syntaxhighlight lang="haskell">import Data.Complex


eulerIdentityZeroIsh :: Complex Double
eulerIdentityZeroIsh :: Complex Double
Line 225: Line 422:
main :: IO ()
main :: IO ()
main = print eulerIdentityZeroIsh</lang>
main = print eulerIdentityZeroIsh</syntaxhighlight>
{{Out}}
{{Out}}


Line 232: Line 429:


=={{header|J}}==
=={{header|J}}==
<syntaxhighlight lang="j">
<lang j>
NB. Euler's number is the default base for power
NB. Euler's number is the default base for power
NB. using j's expressive numeric notation:
NB. using j's expressive numeric notation:
Line 255: Line 452:
1 (=!.1e_15) ^ j. TAU
1 (=!.1e_15) ^ j. TAU
1
1
</syntaxhighlight>
</lang>


=={{header|Java}}==
=={{header|Java}}==
Since Java lacks a complex number class, a class is used that has sufficient operations.
Since Java lacks a complex number class, a class is used that has sufficient operations.
<lang java>
<syntaxhighlight lang="java">
public class EulerIdentity {
public class EulerIdentity {


Line 290: Line 487:
}
}
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 305: Line 502:
be placed in a module to avoid name conflicts, and thus no special
be placed in a module to avoid name conflicts, and thus no special
prefix is used here.
prefix is used here.
<lang jq>def multiply(x; y):
<syntaxhighlight lang="jq">def multiply(x; y):
if (x|type) == "number" then
if (x|type) == "number" then
if (y|type) == "number" then [ x*y, 0 ]
if (y|type) == "number" then [ x*y, 0 ]
Line 331: Line 528:


def pi: 4 * (1|atan);
def pi: 4 * (1|atan);
</syntaxhighlight>
</lang>


===The Task===
===The Task===
<lang jq>"e^iπ: \( exp( [0, pi ] ) )",
<syntaxhighlight lang="jq">"e^iπ: \( exp( [0, pi ] ) )",
"e^iπ + 1: \( plus(1; exp( [0, pi ] ) ))"</lang>
"e^iπ + 1: \( plus(1; exp( [0, pi ] ) ))"</syntaxhighlight>


{{out}}
{{out}}
Line 345: Line 542:
Julia has a builtin <tt>Complex{T}</tt> parametrized type.
Julia has a builtin <tt>Complex{T}</tt> parametrized type.


<lang julia>@show ℯ^(π * im) + 1
<syntaxhighlight lang="julia">@show ℯ^(π * im) + 1
@assert ℯ^(π * im) ≈ -1</lang>
@assert ℯ^(π * im) ≈ -1</syntaxhighlight>


{{out}}
{{out}}
Line 353: Line 550:
Using symbolic algebra, through the [https://github.com/chakravala/Reduce.jl Reduce.jl] package.
Using symbolic algebra, through the [https://github.com/chakravala/Reduce.jl Reduce.jl] package.


<lang julia>using Reduce
<syntaxhighlight lang="julia">using Reduce
@force using Reduce.Algebra
@force using Reduce.Algebra


@show ℯ^(π * :i) + 1
@show ℯ^(π * :i) + 1
@assert ℯ^(π * :i) + 1 == 0</lang>
@assert ℯ^(π * :i) + 1 == 0</syntaxhighlight>


{{out}}
{{out}}
Line 366: Line 563:


e ^ πi is calculated by summing successive terms of the power series for e ^ x until the modulus of the difference between terms is no longer significant given the precision of the Double type (about 10 ^ -16).
e ^ πi is calculated by summing successive terms of the power series for e ^ x until the modulus of the difference between terms is no longer significant given the precision of the Double type (about 10 ^ -16).
<lang scala>// Version 1.2.40
<syntaxhighlight lang="scala">// Version 1.2.40


import kotlin.math.sqrt
import kotlin.math.sqrt
Line 417: Line 614:
e += Complex(1.0, 0.0)
e += Complex(1.0, 0.0)
println("e^${SMALL_PI}i + 1 = $e $APPROX_EQUALS 0")
println("e^${SMALL_PI}i + 1 = $e $APPROX_EQUALS 0")
}</lang>
}</syntaxhighlight>


{{output}}
{{output}}
Line 425: Line 622:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang="scheme">
{require lib_complex}
{require lib_complex}


'{C.exp {C.mul {C.new 0 1} {C.new {PI} 0}}} // e^πi = exp( [π,0] * [0,1] )
'{C.exp {C.mul {C.new 0 1} {C.new {PI} 0}}} // e^πi = exp( [π,0] * [0,1] )
-> (-1 1.2246467991473532e-16) // = -1
-> (-1 1.2246467991473532e-16) // = -1
</syntaxhighlight>
</lang>

=={{header|Lua}}==
<syntaxhighlight lang="lua">local c = {
new = function(s,r,i) s.__index=s return setmetatable({r=r, i=i}, s) end,
add = function(s,o) return s:new(s.r+o.r, s.i+o.i) end,
exp = function(s) local e=math.exp(s.r) return s:new(e*math.cos(s.i), e*math.sin(s.i)) end,
mul = function(s,o) return s:new(s.r*o.r+s.i*o.i, s.r*o.i+s.i*o.r) end
}
local i = c:new(0, 1)
local pi = c:new(math.pi, 0)
local one = c:new(1, 0)
local zero = i:mul(pi):exp():add(one)
print(string.format("e^(i*pi)+1 is approximately zero: %.18g%+.18gi", zero.r, zero.i))</syntaxhighlight>
{{out}}
<pre>e^(i*pi)+1 is approximately zero: 0+1.22460635382237726e-016i</pre>
<syntaxhighlight lang="lua">> -- alternatively, equivalent one-liner from prompt:
> math.exp(0)*math.cos(math.pi)+1, math.exp(0)*math.sin(math.pi)
0.0 1.2246063538224e-016</syntaxhighlight>

=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">E^(I Pi) + 1</syntaxhighlight>
{{out}}
<pre>0</pre>

=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
is(equal(%e^(%i*%pi)+1,0));
</syntaxhighlight>
{{out}}
<pre>
true
</pre>

=={{header|Nim}}==
<syntaxhighlight lang="nim">import math, complex

echo "exp(iπ) + 1 = ", exp(complex(0.0, PI)) + 1, " ~= 0"</syntaxhighlight>


=={{header|Mathematica}}==
<lang Mathematica>E^(I Pi) + 1 == 0</lang>
{{out}}
{{out}}
<pre>exp(iπ) + 1 = (0.0, 1.224646799147353e-16) ~= 0</pre>
<pre>True</pre>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml># open Complex;;
<syntaxhighlight lang="ocaml"># open Complex;;
# let pi = acos (-1.0);;
# let pi = acos (-1.0);;
val pi : float = 3.14159265358979312
val pi : float = 3.14159265358979312
# add (exp { re = 0.0; im = pi }) { re = 1.0; im = 0.0 };;
# add (exp { re = 0.0; im = pi }) { re = 1.0; im = 0.0 };;
- : Complex.t = {re = 0.; im = 1.22464679914735321e-16}</lang>
- : Complex.t = {re = 0.; im = 1.22464679914735321e-16}</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>use Math::Complex;
<syntaxhighlight lang="perl">use Math::Complex;
print exp(pi * i) + 1, "\n";</lang>
print exp(pi * i) + 1, "\n";</syntaxhighlight>
{{out}}
{{out}}
<pre>1.22464679914735e-16i</pre>
<pre>1.22464679914735e-16i</pre>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>include builtins\complex.e -- (0.8.0+)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
complex res = complex_add(complex_exp(complex_mul(PI,I)),1)
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #004080;">complex</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
?complex_sprint(res,both:=true)
<span style="color: #004080;">complex</span> <span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">complex_new</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">),</span>
?complex_sprint(complex_round(res,1e16),true)
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">complex_add</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">complex_exp</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">complex_mul</span><span style="color: #0000FF;">(</span><span style="color: #004600;">PI</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)),</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
?complex_sprint(complex_round(res,1e15))</lang>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">complex_sprint</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">both</span><span style="color: #0000FF;">:=</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">complex_sprint</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">complex_round</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1e16</span><span style="color: #0000FF;">),</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">complex_sprint</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">complex_round</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1e15</span><span style="color: #0000FF;">),</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
{{out}}
The actual result and two rounded versions (to prove the rounding is doing what it should - the second arg is an inverted precision).
The actual result and two rounded versions (to prove the rounding is doing what it should - the second arg is an inverted precision).
Line 461: Line 697:
"0+1.2246e-16i"
"0+1.2246e-16i"
"0+1e-16i"
"0+1e-16i"
"0"
"0+0i"
</pre>
{{trans|Prolog}}
Of course "symbolically" you can just do this (ha ha):
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">reduce</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">rules</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #008000;">"-1+1"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"0"</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #008000;">"-1+0"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"-1"</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #008000;">"i*0"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"0"</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #008000;">"sin(pi)"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"0"</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #008000;">"cos(pi)"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"-1"</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #008000;">"exp(i*pi)"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"cos(pi)+i*sin(pi)"</span><span style="color: #0000FF;">}}</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">seen</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span> <span style="color: #000080;font-style:italic;">-- (be safe and avoid infinite loops)</span>
<span style="color: #008080;">while</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">seen</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- "" re-treading</span>
<span style="color: #008080;">and</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">10000</span> <span style="color: #008080;">do</span> <span style="color: #000080;font-style:italic;">-- "" ever-growing</span>
<span style="color: #000000;">seen</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">seen</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">bool</span> <span style="color: #000000;">found</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rules</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">string</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">rules</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">match</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">found</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">true</span>
<span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">substitute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">found</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s = %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t</span><span style="color: #0000FF;">})</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">reduce</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"exp(i*pi)+1"</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
exp(i*pi)+1 = cos(pi)+i*sin(pi)+1
= -1+i*0+1
= -1+0+1
= -1+1
= 0
</pre>

=={{header|Prolog}}==
Symbolically manipulates Euler's identity until it can't be further reduced (and we get zero :)
<syntaxhighlight lang="prolog">
% reduce() prints the intermediate results so that one can see Prolog "thinking."
%
reduce(A, C) :-
simplify(A, B),
(B = A -> C = A; io:format("= ~w~n", [B]), reduce(B, C)).

simplify(exp(i*X), cos(X) + i*sin(X)) :- !.

simplify(0 + A, A) :- !.
simplify(A + 0, A) :- !.
simplify(A + B, C) :-
integer(A),
integer(B), !,
C is A + B.
simplify(A + B, C + D) :- !,
simplify(A, C),
simplify(B, D).

simplify(0 * _, 0) :- !.
simplify(_ * 0, 0) :- !.
simplify(1 * A, A) :- !.
simplify(A * 1, A) :- !.
simplify(A * B, C) :-
integer(A),
integer(B), !,
C is A * B.
simplify(A * B, C * D) :- !,
simplify(A, C),
simplify(B, D).

simplify(cos(0), 1) :- !.
simplify(sin(0), 0) :- !.
simplify(cos(pi), -1) :- !.
simplify(sin(pi), 0) :- !.

simplify(X, X).
</syntaxhighlight>
{{Out}}
<pre>
?- reduce(exp(i*pi)+1, X).
= cos(pi)+i*sin(pi)+1
= -1+i*0+1
= -1+0+1
= -1+1
= 0
X = 0.
</pre>
</pre>


=={{header|Python}}==
=={{header|Python}}==
<lang python>>>> import math
<syntaxhighlight lang="python">>>> import math
>>> math.e ** (math.pi * 1j) + 1
>>> math.e ** (math.pi * 1j) + 1
1.2246467991473532e-16j</lang>
1.2246467991473532e-16j</syntaxhighlight>

=={{header|R}}==
<syntaxhighlight lang="r"># lang R
exp(1i * pi) + 1</syntaxhighlight>
{{out}}<pre>0+1.224606e-16i</pre>

Symbolically with the Ryacas package (on CRAN):
<syntaxhighlight lang="r">library(Ryacas)
as_r(yac_str("Exp(I * Pi) + 1"))</syntaxhighlight>
{{out}}<pre>0</pre>


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>#lang racket
<syntaxhighlight lang="racket">#lang racket
(+ (exp (* 0+i pi)) 1)</lang>
(+ (exp (* 0+i pi)) 1)</syntaxhighlight>
{{out}}<pre>0.0+1.2246063538223773e-016i</pre>
{{out}}<pre>0.0+1.2246063538223773e-016i</pre>


Line 481: Line 818:
e, i and π are all available as built-in constants in Raku.
e, i and π are all available as built-in constants in Raku.


<lang perl6>sub infix:<⁢> is tighter(&infix:<**>) { $^a * $^b };
<syntaxhighlight lang="raku" line>sub infix:<⁢> is tighter(&infix:<**>) { $^a * $^b };


say 'e**i⁢π + 1 ≅ 0 : ', e**i⁢π + 1 ≅ 0;
say 'e**i⁢π + 1 ≅ 0 : ', e**i⁢π + 1 ≅ 0;
say 'Error: ', e**i⁢π + 1;</lang>
say 'Error: ', e**i⁢π + 1;</syntaxhighlight>
{{out}}
{{out}}
<pre>e**i⁢π + 1 ≅ 0 : True
<pre>e**i⁢π + 1 ≅ 0 : True
Line 525: Line 862:
of &nbsp; pi &nbsp; being defined within the REXX
of &nbsp; pi &nbsp; being defined within the REXX
<br>program.
<br>program.
<lang rexx>/*REXX program proves Euler's identity by showing that: e^(i pi) + 1 ≡ 0 */
<syntaxhighlight lang="rexx">/*REXX program proves Euler's identity by showing that: e^(i pi) + 1 ≡ 0 */
numeric digits length( pi() ) - length(.) /*define pi; set # dec. digs precision*/
numeric digits length( pi() ) - length(.) /*define pi; set # dec. digs precision*/
cosPI= fmt( cos(pi) ) /*calculate the value of cos(pi). */
cosPI= fmt( cos(pi) ) /*calculate the value of cos(pi). */
Line 547: Line 884:
parse value format(x, 2, 1, , 0) 'E0' with g 'E' _ .; g= g * .5'e'_ % 2
parse value format(x, 2, 1, , 0) 'E0' with g 'E' _ .; g= g * .5'e'_ % 2
do j=0 while h>9; m.j= h; h= h % 2 + 1; end
do j=0 while h>9; m.j= h; h= h % 2 + 1; end
do k=j+5 to 0 by -1; numeric digits m.k; g= (g+x/g) *.5; end; return g || i</lang>
do k=j+5 to 0 by -1; numeric digits m.k; g= (g+x/g) *.5; end; return g || i</syntaxhighlight>
{{out|output|text=&nbsp; when using the internal default input:}}
{{out|output|text=&nbsp; when using the internal default input:}}
<pre>
<pre>
Line 563: Line 900:
<br>programmatically invoked with the requested number of decimal digits).
<br>programmatically invoked with the requested number of decimal digits).


<lang rexx>/*────────────────── 1,051 decimal digs of pi. ──────────────────*/
<syntaxhighlight lang="rexx">/*────────────────── 1,051 decimal digs of pi. ──────────────────*/


pi= 3.14159265358979323846264338327950288419716939937510
pi= 3.14159265358979323846264338327950288419716939937510
Line 585: Line 922:
pi= pi || 59825349042875546873115956286388235378759375195778
pi= pi || 59825349042875546873115956286388235378759375195778
pi= pi || 18577805321712268066130019278766111959092164201989
pi= pi || 18577805321712268066130019278766111959092164201989
pi= pi || 38095257201065485863278865936153381827968230301952 </lang>
pi= pi || 38095257201065485863278865936153381827968230301952 </syntaxhighlight>

=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
'EXP(i*π)+1' →NUM ABS
{{out}}
<pre>
1.22464679915E-16
</pre>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>
<syntaxhighlight lang="ruby">
include Math
Math::E ** (Math::PI * 1i) + 1

# => (0.0+0.0i)</lang>
E ** (PI * 1i) + 1
# => (0.0+0.0i)</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>use std::f64::consts::PI;
<syntaxhighlight lang="rust">use std::f64::consts::PI;


extern crate num_complex;
extern crate num_complex;
Line 600: Line 947:
fn main() {
fn main() {
println!("{:e}", Complex::new(0.0, PI).exp() + 1.0);
println!("{:e}", Complex::new(0.0, PI).exp() + 1.0);
}</lang>
}</syntaxhighlight>


{{output}}
{{output}}
Line 610: Line 957:
This example makes use of Spire's numeric data types. Complex takes a type parameter determining the type of the coefficients of a + bi, and Real is Spire's exact (i.e. arbitrary precision) numeric data type.
This example makes use of Spire's numeric data types. Complex takes a type parameter determining the type of the coefficients of a + bi, and Real is Spire's exact (i.e. arbitrary precision) numeric data type.


<lang scala>import spire.math.{Complex, Real}
<syntaxhighlight lang="scala">import spire.math.{Complex, Real}


object Scratch extends App{
object Scratch extends App{
Line 620: Line 967:
println(e.pow(pi*i) + one)
println(e.pow(pi*i) + one)
}</lang>
}</syntaxhighlight>


{{output}}
{{output}}
Line 626: Line 973:
(0 + 0i)
(0 + 0i)
</pre>
</pre>
=={{header|Scheme}}==
{{works with|Chez Scheme}}
<syntaxhighlight lang="scheme">; A way to get pi.
(define pi (acos -1))

; Print the value of e^(i*pi) + 1 -- should be 0.
(printf "e^(i*pi) + 1 = ~a~%" (+ (exp (* +i pi)) 1))</syntaxhighlight>
{{out}}
<pre>e^(i*pi) + 1 = 0.0+1.2246467991473532e-16i
</pre>
{{works with|Chez Scheme}}
A higher precision test using series approximations to Pi and the Exp() function.
The series are computed using exact rational numbers.
This code converts the rational results into decimal representation.
<syntaxhighlight lang="scheme">; Procedure to compute factorial.

(define fact
(lambda (n)
(if (<= n 0)
1
(* n (fact (1- n))))))

; Use series to compute approximation to Pi (using N terms of series).
; (Uses the Newton / Euler Convergence Transformation.)

(define pi-series
(lambda (n)
(do ((k 0 (1+ k))
(sum 0 (+ sum (/ (* (expt 2 k) (expt (fact k) 2)) (fact (1+ (* 2 k)))))))
((>= k n) (* 2 sum)))))

; Use series to compute approximation to exp(z) (using N terms of series).

(define exp-series
(lambda (z n)
(do ((k 0 (1+ k))
(sum 0 (+ sum (/ (expt z k) (fact k)))))
((>= k n) sum))))

; Convert the given Rational number to a Decimal string.
; If opt contains an integer, show to that many places past the decimal regardless of repeating.
; If opt contains 'nopar, do not insert the parentheses indicating the repeating places.
; If opt contains 'plus, prefix positive numbers with plus ('+') sign.
; N.B.: When number of decimals specified, this truncates instead of rounds.

(define rat->dec-str
(lambda (rat . opt)
(let* ((num (abs (numerator rat)))
(den (abs (denominator rat)))
(no-par (find (lambda (a) (eq? a 'nopar)) opt))
(plus (find (lambda (a) (eq? a 'plus)) opt))
(dec-lim (find integer? opt))
(rep-inx #f)
(rems-seen '())
(int-part (format (cond ((< rat 0) "-~d") (plus "+~d") (else "~d")) (quotient num den)))
(frc-list
(cond
((zero? num)
'())
(else
(let loop ((rem (modulo num den)) (decs 0))
(cond
((or (<= rem 0) (and dec-lim (>= decs dec-lim)))
'())
((and (not dec-lim) (assq rem rems-seen))
(set! rep-inx (cdr (assq rem rems-seen)))
'())
(else
(set! rems-seen (cons (cons rem decs) rems-seen))
(cons
(integer->char (+ (quotient (* 10 rem) den) (char->integer #\0)))
(loop (modulo (* 10 rem) den) (1+ decs))))))))))
(when (and rep-inx (not no-par))
(set! frc-list (append
(list-head frc-list rep-inx)
(list #\()
(list-tail frc-list rep-inx)
(list #\)))))
(if (null? frc-list)
int-part
(format "~a.~a" int-part (list->string frc-list))))))

; Convert the given Rational Complex number to a Decimal string.
; If opt contains an integer, show to that many places past the decimal regardless of repeating.
; If opt contains 'nopar, do not insert the parentheses indicating the repeating places.
; If opt contains 'plus, prefix positive numbers with plus ('+') sign.
; N.B.: When number of decimals specified, this truncates instead of rounds.

(define rat-cplx->dec-str
(lambda (rat-cplx . opt)
(let* ((real-dec-str (apply rat->dec-str (cons (real-part rat-cplx) opt)))
(imag-dec-str (apply rat->dec-str (cons (imag-part rat-cplx) (cons 'plus opt)))))
(format "~a~ai" real-dec-str imag-dec-str))))

; Print the value of e^(i*pi) + 1 -- should be 0.
; (Computed using the series defined above.)

(let*
((pi (pi-series 222))
(e-pi-i (exp-series (* pi +i) 222))
(euler-id (+ e-pi-i 1)))
(printf "e^(i*pi) + 1 = ~a~%" (rat-cplx->dec-str euler-id 70)))</syntaxhighlight>
{{out}}
<pre>e^(i*pi) + 1 =
0.0000000000000000000000000000000000000000000000000000000000000000000000
+0.0000000000000000000000000000000000000000000000000000000000000000000351i</pre>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>say ('e**i⁢π + 1 ≅ 0 : ', Num.e**Num.pi.i + 1 ≅ 0)
<syntaxhighlight lang="ruby">say ('e**i⁢π + 1 ≅ 0 : ', Num.e**Num.pi.i + 1 ≅ 0)
say ('Error: ', Num.e**Num.pi.i + 1)</lang>
say ('Error: ', Num.e**Num.pi.i + 1)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 638: Line 1,091:
=={{header|Tcl}}==
=={{header|Tcl}}==
=== Using tcllib ===
=== Using tcllib ===
<lang tcl># Set up complex sandbox (since we're doing a star import)
<syntaxhighlight lang="tcl"># Set up complex sandbox (since we're doing a star import)
namespace eval complex_ns {
namespace eval complex_ns {
package require math::complexnumbers
package require math::complexnumbers
Line 647: Line 1,100:
set r [+ [exp [complex 0 $pi]] [complex 1 0]]
set r [+ [exp [complex 0 $pi]] [complex 1 0]]
puts "e**(pi*i) = [real $r]+[imag $r]i"
puts "e**(pi*i) = [real $r]+[imag $r]i"
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 654: Line 1,107:


=== Using VecTcl ===
=== Using VecTcl ===
<lang tcl>package require vectcl
<syntaxhighlight lang="tcl">package require vectcl
namespace import vectcl::vexpr
namespace import vectcl::vexpr


set ans [vexpr {pi=acos(-1); exp(pi*1i) + 1}]
set ans [vexpr {pi=acos(-1); exp(pi*1i) + 1}]
puts "e**(pi*i) = $ans"
puts "e**(pi*i) = $ans"
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 666: Line 1,119:


=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-complex}}
As complex numbers are not built in, we create a bare-bones Complex class with only the methods we need to complete this task.
<lang ecmascript>class Num2 {
static exp(x) {
var e = 2.718281828459045
return e.pow(x)
}
}

class Complex {
construct new(real, imag) {
_real = real
_imag = imag
}

real { _real }
imag { _imag }


<syntaxhighlight lang="wren">import "./complex" for Complex
+ (other) { Complex.new(_real + other.real, _imag + other.imag) }

exp {
var re = Num2.exp(_real)
return Complex.new(re * _imag.cos, re * _imag.sin)
}

toString { (_imag >= 0) ? "%(_real) + %(_imag)i" : "%(_real) - %(-_imag)i" }

static one { Complex.new(1, 0) }
}


System.print((Complex.new(0, Num.pi).exp + Complex.one).toString)</lang>
System.print((Complex.new(0, Num.pi).exp + Complex.one).toString)</syntaxhighlight>


{{out}}
{{out}}
Line 703: Line 1,131:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
<syntaxhighlight lang="zkl">var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
Z,pi,e := GSL.Z, (0.0).pi, (0.0).e;
Z,pi,e := GSL.Z, (0.0).pi, (0.0).e;


println("e^(\u03c0i) + 1 = %s \u2245 0".fmt( Z(e).pow(Z(0,1)*pi) + 1 ));
println("e^(\u03c0i) + 1 = %s \u2245 0".fmt( Z(e).pow(Z(0,1)*pi) + 1 ));
println("TMI: ",(Z(e).pow(Z(0,1)*pi) + 1 ).format(0,25,"g"));</lang>
println("TMI: ",(Z(e).pow(Z(0,1)*pi) + 1 ).format(0,25,"g"));</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>

Latest revision as of 11:21, 30 November 2023

Task
Euler's identity
You are encouraged to solve this task according to the task description, using any language you may know.
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)


In mathematics, Euler's identity is the equality:

               ei + 1 = 0

where

   e is Euler's number, the base of natural logarithms,
   i is the imaginary unit, which satisfies i2 = −1, and
    is pi, the ratio of the circumference of a circle to its diameter.

Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:

   The number 0.
   The number 1.
   The number  ( = 3.14159+),
   The number e (e = 2.71828+), which occurs widely in mathematical analysis.
   The number i, the imaginary unit of the complex numbers.
Task

Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.

Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.

If that is the case, or there is some other limitation, show that ei + 1 is approximately equal to zero and show the amount of error in the calculation.

If your language is capable of symbolic calculations, show that ei + 1 is exactly equal to zero for bonus kudos points.

11l

Translation of: Python
print(math:e ^ (math:pi * 1i) + 1)
Output:
1.22465e-16i

Ada

with Ada.Long_Complex_Text_IO; use Ada.Long_Complex_Text_IO;
with Ada.Numerics; use Ada.Numerics;
with Ada.Numerics.Long_Complex_Types; use Ada.Numerics.Long_Complex_Types;
with Ada.Numerics.Long_Complex_Elementary_Functions; use Ada.Numerics.Long_Complex_Elementary_Functions;
procedure Eulers_Identity is
begin
   Put (Exp (Pi * i) + 1.0);
end Eulers_Identity;
Output:
( 0.00000000000000E+00, 1.22464679914735E-16)

ALGOL 68

Whilst Algol 68 has complex numbers as standard, it does not have a standard complex exp function.
We could use the identity exp(x + iy) = exp(x)( cos y + i sin y ), however the following uses a series expansion for exp(ix).

BEGIN
    # calculate an approximation to e^(i pi) + 1 which should be 0 (Euler's identity) #

    # returns e^ix for long real x, using the series:                                 #
    #      exp(ix) = 1 - x^2/2! + x^4/4! - ... + i(x - x^3/3! + x^5/5! - x^7/7! ... ) #
    #      the expansion stops when successive terms differ by less than 1e-15        #
    PROC expi = ( LONG REAL x )LONG COMPL:
         BEGIN
            LONG REAL t              := 1;
            LONG REAL real part      := 1;
            LONG REAL imaginary part := 0;
            LONG REAL divisor        := 1;
            BOOL      even power     := FALSE;
            BOOL      subtract       := FALSE;
            LONG REAL diff           := 1;
            FOR n FROM 1 WHILE ABS diff > 1e-15 DO
                divisor *:= n;
                t       *:= x;
                LONG REAL term := t / divisor;
                IF even power THEN
                    # this term is real #
                    subtract := NOT subtract;
                    LONG REAL prev := real part;
                    IF subtract THEN
                        real part -:= term
                    ELSE
                        real part +:= term
                    FI;
                    diff := prev - real part
                ELSE
                    # this term is imaginary #
                    LONG REAL prev := imaginary part;
                    IF subtract THEN
                        imaginary part -:= term
                    ELSE
                        imaginary part +:= term
                    FI;
                    diff := prev - imaginary part
                FI;
                even power := NOT even power
            OD;
            ( real part, imaginary part )
         END # expi # ;
    LONG COMPL eulers identity = expi( long pi ) + 1;
    print( ( "e^(i*pi) + 1 ~ "
           , fixed( re OF eulers identity, -23, 20 )
           , " "
           , fixed( im OF eulers identity,  23, 20 )
           , "i"
           , newline
           )
         )
END
Output:
e^(i*pi) + 1 ~  0.00000000000000000307 -0.00000000000000002926i

Bracmat

e^(i*pi)+1

By symbolic calculation:

0

C

The C99 standard did, of course, introduce built-in support for complex number arithmetic into the language and so we can therefore compute (e ^ πi + 1) directly without having to resort to methods which sum the power series for e ^ x.

The following code has been tested with gcc 5.4.0 on Ubuntu 16.04.

#include <stdio.h>
#include <math.h>
#include <complex.h>
#include <wchar.h>
#include <locale.h>

int main() {
    wchar_t pi = L'\u03c0'; /* Small pi symbol */
    wchar_t ae = L'\u2245'; /* Approximately equals symbol */
    double complex e = cexp(M_PI * I) + 1.0;
    setlocale(LC_CTYPE, "");
    printf("e ^ %lci + 1 = [%.16f, %.16f] %lc 0\n", pi, creal(e), cimag(e), ae);
    return 0;
}
Output:
e ^ πi + 1 = [0.0000000000000000, 0.0000000000000001] ≅ 0

C#

using System;
using System.Numerics;

public class Program
{
    static void Main() {
        Complex e = Math.E;
        Complex i = Complex.ImaginaryOne;
        Complex π = Math.PI;
        Console.WriteLine(Complex.Pow(e, i * π) + 1);
    }
}
Output:
(0, 1.22464679914735E-16)

C++

#include <iostream>
#include <complex>

int main() {
  std::cout << std::exp(std::complex<double>(0.0, M_PI)) + 1.0 << std::endl;
  return 0;
}
Output:

Zero and a little floating dust ...

(0,1.22465e-16)

Common Lisp

Common Lisp has complex number arithmetic built into it.

(+ 1 (exp (complex 0 pi)))
#C(0.0L0 -5.0165576136843360246L-20)

Delphi

program Euler_identity;

{$APPTYPE CONSOLE}

uses
  System.VarCmplx;

begin
  var result := VarComplexExp(Pi * VarComplexCreate(0, 1)) + 1;
  writeln(result);
  readln;
end.
Output:
0 + 0i

F#

As per the discussion page this task as described is to show that -1+1=0

printfn "-1 + 1 = %d" (-1+1)
Output:
-1 + 1 = 0

I shall also show that cos π = -1 and sin π = 0

printfn "cos(pi)=%f and sin(pi)=%f" (cos 3.141592653589793) (sin 3.141592653589793)
Output:
cos(pi)=-1.000000 and sin(pi)=0.000000

I shall try the formula e. I'll use the MathNet.Numerics package. I'll leave you the reader to determine what it 'proves'.

let i =MathNet.Numerics.complex(0.0,1.0);;
let pi=MathNet.Numerics.complex(MathNet.Numerics.Constants.Pi,0.0);;
let e =MathNet.Numerics.complex(MathNet.Numerics.Constants.E ,0.0);;
printfn "e**(i*pi) = %A" (e**(i*pi));;
Output:
e**(i*pi) = (-1, 1.2246467991473532E-16)

Factor

USING: math math.constants math.functions prettyprint ;
1 e pi C{ 0 1 } * ^ + .
Output:
C{ 0.0 1.224646799147353e-016 }

Forth

Uses fs. (scientific) to print the imaginary term, since that's the one that's inexact.

." e^(i*π) + 1 = " pi fcos 1e0 f+ f. '+ emit space pi fsin fs. 'i emit cr
bye
Output:
e^(i*π) + 1 = 0. + 1.22464679914735E-16 i

Fortran

program euler
    use iso_fortran_env, only: output_unit, REAL64
    implicit none

    integer, parameter              :: d=REAL64
    real(kind=d), parameter         :: e=exp(1._d), pi=4._d*atan(1._d)
    complex(kind=d), parameter      :: i=(0._d,1._d)

    write(output_unit,*) e**(pi*i) + 1
end program euler
Output:
         (0.0000000000000000,2.89542045005908316E-016)

FreeBASIC

Provides complex arithmetic and a very rapidly converging algorithm for e^z.

#define PI 3.141592653589793238462643383279502884197169399375105821
#define MAXITER 12

'---------------------------------------
'   complex numbers and their arithmetic
'---------------------------------------

type complex
    r as double
    i as double
end type

function conj( a as complex ) as complex
    dim as complex c
    c.r =  a.r
    c.i = -a.i
    return c
end function

operator + ( a as complex, b as complex ) as complex
    dim as complex c
    c.r = a.r + b.r
    c.i = a.i + b.i
    return c
end operator

operator - ( a as complex, b as complex ) as complex
    dim as complex c
    c.r = a.r - b.r
    c.i = a.i - b.i
    return c
end operator

operator * ( a as complex, b as complex ) as complex
    dim as complex c
    c.r = a.r*b.r - a.i*b.i
    c.i = a.i*b.r + a.r*b.i
    return c
end operator

operator / ( a as complex, b as complex ) as complex
    dim as double bcb = (b*conj(b)).r
    dim as complex acb = a*conj(b), c 
    c.r = acb.r/bcb
    c.i = acb.i/bcb
    return c
end operator

sub printc( a as complex )
    if a.i>=0 then
        print using "############.############### + ############.############### i"; a.r; a.i
    else
        print using "############.############### - ############.############### i"; a.r; -a.i
    end if
end sub

function intc( n as integer ) as complex
    dim as complex c
    c.r = n
    c.i = 0.0
    return c
end function

function absc( a as complex ) as double
    return sqr( (a*conj(a)).r )
end function

'-----------------------
' the algorithm
' Uses a rapidly converging continued
' fraction expansion for e^z and recursive
' expressions for its convergents
'-----------------------

dim as complex pii, pii2, curr, A2, A1, A0, B2, B1, B0
dim as complex ONE, TWO
dim as integer i, k = 2
pii.r = 0.0
pii.i = PI
pii2 = pii*pii

B0 = intc(2)
A0 = intc(2)
B1 = (intc(2) - pii)
A1 = B0*B1 + intc(2)*pii
printc( A0/B0)
print "     Absolute error = ", absc(A0/B0)
printc( A1/B1)
print "     Absolute error = ", absc(A1/B1)

for i = 1 to MAXITER
    k = k + 4
    A2 = intc(k)*A1 + pii2*A0
    B2 = intc(k)*B1 + pii2*B0
    curr = A2/B2
    A0 = A1
    A1 = A2
    B0 = B1
    B1 = B2
    printc( curr  )
    print "     Absolute error = ", absc(curr)
next i

Go

package main
 
import (
    "fmt"
    "math"
    "math/cmplx"
)
 
func main() {
    fmt.Println(cmplx.Exp(math.Pi * 1i) + 1.0)
}
Output:

Zero and a little floating dust ...

(0+1.2246467991473515e-16i)

Groovy

Because the Groovy language does not provide a built-in facility for complex arithmetic, this example relies on the Complex class defined in the Complex numbers example.

import static Complex.*

Number.metaClass.mixin ComplexCategory

def π = Math.PI
def e = Math.E

println "e ** (π * i) + 1 = " + (e ** (π * i) + 1)

println "| e ** (π * i) + 1 | = " + (e ** (π * i) + 1).ρ

Output: (yadda, yadda, dust, yadda)

e ** (π * i) + 1 = 1.2246467991473532E-16i
| e ** (π * i) + 1 | = 1.2246467991473532E-16

Haskell

A double is not quite real.

import Data.Complex

eulerIdentityZeroIsh :: Complex Double
eulerIdentityZeroIsh =
  exp (0 :+ pi) + 1
  
main :: IO ()
main = print eulerIdentityZeroIsh
Output:

Zero and a little floating dust ...

0.0 :+ 1.2246467991473532e-16

J

   NB. Euler's number is the default base for power
   NB. using j's expressive numeric notation:
   1 + ^ 0j1p1
0j1.22465e_16
   

   NB. Customize the comparison tolerance to 10 ^ (-15)
   NB. to show that
   _1 (=!.1e_15) ^ 0j1p1
1


   
   TAU =: 2p1

   NB. tauday.com  pi is wrong
   NB. with TAU as 2 pi,
   NB. Euler's identity should have read


   1 (=!.1e_15) ^ j. TAU
1

Java

Since Java lacks a complex number class, a class is used that has sufficient operations.

public class EulerIdentity {

    public static void main(String[] args) {
        System.out.println("e ^ (i*Pi) + 1 = " + (new Complex(0, Math.PI).exp()).add(new Complex(1, 0)));
    }

    public static class Complex {

        private double x, y;
        
        public Complex(double re, double im) {
            x = re;
            y = im;
        }
        
        public Complex exp() {
            double exp = Math.exp(x);
            return new Complex(exp * Math.cos(y), exp * Math.sin(y));
        }
        
        public Complex add(Complex a) {
            return new Complex(x + a.x, y + a.y);
        }
        
        @Override
        public String toString() {
            return x + " + " + y + "i";
        }
    }
}
Output:
e ^ (i*Pi) + 1 = 0.0 + 1.2246467991473532E-16i

jq

For speed and for conformance with the complex plane interpretation, x+iy is represented as [x,y]; for flexibility, all the functions defined here will accept both real and complex numbers, and for uniformity, they are implemented as functions that ignore their input.

Recent versions of jq support modules, so these functions could all be placed in a module to avoid name conflicts, and thus no special prefix is used here.

def multiply(x; y):
    if (x|type) == "number" then
       if  (y|type) == "number" then [ x*y, 0 ]
       else [x * y[0], x * y[1]]
       end
    elif (y|type) == "number" then multiply(y;x)
    else [ x[0] * y[0] - x[1] * y[1],  x[0] * y[1] + x[1] * y[0]]
    end;

def plus(x; y):
    if (x|type) == "number" then
       if  (y|type) == "number" then [ x+y, 0 ]
       else [ x + y[0], y[1]]
       end
    elif (y|type) == "number" then plus(y;x)
    else [ x[0] + y[0], x[1] + y[1] ]
    end;

def exp(z):
  def expi(x): [ (x|cos), (x|sin) ];
  if (z|type) == "number" then z|exp
  elif z[0] == 0 then expi(z[1])  # for efficiency
  else multiply( (z[0]|exp); expi(z[1]) )
  end ;

def pi: 4 * (1|atan);

The Task

"e^iπ:     \( exp( [0, pi ] ) )",
"e^iπ + 1: \( plus(1; exp( [0, pi ] ) ))"
Output:
e^iπ:     [-1,1.2246467991473532e-16]
e^iπ + 1: [0,1.2246467991473532e-16]

Julia

Works with: Julia version 1.2

Julia has a builtin Complex{T} parametrized type.

@show ^(π * im) + 1
@assert ^(π * im)  -1
Output:
e ^ (π * im) + 1 = 0.0 + 1.2246467991473532e-16im

Using symbolic algebra, through the Reduce.jl package.

using Reduce
@force using Reduce.Algebra

@show ^(π * :i) + 1
@assert ^(π * :i) + 1 == 0
Output:
ℯ^(π * :i) + 1 = 0

Kotlin

As the JVM lacks a complex number class, we use our own which has sufficient operations to perform this task.

e ^ πi is calculated by summing successive terms of the power series for e ^ x until the modulus of the difference between terms is no longer significant given the precision of the Double type (about 10 ^ -16).

// Version 1.2.40

import kotlin.math.sqrt
import kotlin.math.PI

const val EPSILON = 1.0e-16
const val SMALL_PI = '\u03c0'
const val APPROX_EQUALS = '\u2245'

class Complex(val real: Double, val imag: Double) {
    operator fun plus(other: Complex) =
        Complex(real + other.real, imag + other.imag)

    operator fun times(other: Complex) = Complex(
        real * other.real - imag * other.imag,
        real * other.imag + imag * other.real
    )

    fun inv(): Complex {
        val denom = real * real + imag * imag
        return Complex(real / denom, -imag / denom)
    }

    operator fun unaryMinus() = Complex(-real, -imag)

    operator fun minus(other: Complex) = this + (-other)

    operator fun div(other: Complex) = this * other.inv()

    val modulus: Double get() = sqrt(real * real + imag * imag)

    override fun toString() =
        if (imag >= 0.0) "$real + ${imag}i"
        else "$real - ${-imag}i"
}

fun main(args: Array<String>) {
    var fact = 1.0
    val x = Complex(0.0, PI)
    var e = Complex(1.0, PI)
    var n = 2
    var pow = x
    do {
        val e0 = e
        fact *= n++
        pow *= x
        e += pow / Complex(fact, 0.0)
    }
    while ((e - e0).modulus >= EPSILON)
    e += Complex(1.0, 0.0)
    println("e^${SMALL_PI}i + 1 = $e $APPROX_EQUALS 0")
}
Output:
e^πi + 1 = -8.881784197001252E-16 - 9.714919754267985E-17i ≅ 0

Lambdatalk

{require lib_complex}

'{C.exp {C.mul {C.new 0 1} {C.new {PI} 0}}}  // e^πi = exp( [π,0] * [0,1] )
-> (-1 1.2246467991473532e-16)               //      = -1

Lua

local c = {
  new = function(s,r,i) s.__index=s return setmetatable({r=r, i=i}, s) end,
  add = function(s,o) return s:new(s.r+o.r, s.i+o.i) end,
  exp = function(s) local e=math.exp(s.r) return s:new(e*math.cos(s.i), e*math.sin(s.i)) end,
  mul = function(s,o) return s:new(s.r*o.r+s.i*o.i, s.r*o.i+s.i*o.r) end
}
local i = c:new(0, 1)
local pi = c:new(math.pi, 0)
local one = c:new(1, 0)
local zero = i:mul(pi):exp():add(one)
print(string.format("e^(i*pi)+1 is approximately zero:  %.18g%+.18gi", zero.r, zero.i))
Output:
e^(i*pi)+1 is approximately zero:  0+1.22460635382237726e-016i
> -- alternatively, equivalent one-liner from prompt:
> math.exp(0)*math.cos(math.pi)+1, math.exp(0)*math.sin(math.pi)
0.0     1.2246063538224e-016

Mathematica/Wolfram Language

E^(I Pi) + 1
Output:
0

Maxima

is(equal(%e^(%i*%pi)+1,0));
Output:
true

Nim

import math, complex

echo "exp(iπ) + 1 = ", exp(complex(0.0, PI)) + 1, " ~= 0"
Output:
exp(iπ) + 1 = (0.0, 1.224646799147353e-16) ~= 0

OCaml

# open Complex;;
# let pi = acos (-1.0);;
val pi : float = 3.14159265358979312
# add (exp { re = 0.0; im = pi }) { re = 1.0; im = 0.0 };;
- : Complex.t = {re = 0.; im = 1.22464679914735321e-16}

Perl

use Math::Complex;
print exp(pi * i) + 1, "\n";
Output:
1.22464679914735e-16i

Phix

with javascript_semantics
include builtins\complex.e
complex i = complex_new(0,1),
        res = complex_add(complex_exp(complex_mul(PI,i)),1)
?complex_sprint(res,both:=true)
?complex_sprint(complex_round(res,1e16),true)
?complex_sprint(complex_round(res,1e15),true)
Output:

The actual result and two rounded versions (to prove the rounding is doing what it should - the second arg is an inverted precision).

"0+1.2246e-16i"
"0+1e-16i"
"0+0i"
Translation of: Prolog

Of course "symbolically" you can just do this (ha ha):

with javascript_semantics
procedure reduce(string s)
    constant rules = {{"-1+1","0"},
                      {"-1+0","-1"},
                      {"i*0","0"},
                      {"sin(pi)","0"},
                      {"cos(pi)","-1"},
                      {"exp(i*pi)","cos(pi)+i*sin(pi)"}}
    string t = s
    sequence seen = {}          -- (be safe and avoid infinite loops)
    while not find(t,seen)      --      "" re-treading
      and length(t)<10000 do    --      "" ever-growing
        seen = append(seen,t)
        bool found = false
        for i=1 to length(rules) do
            string {r,e} = rules[i]
            if match(r,t) then
                found = true
                t = substitute(t,r,e)
            end if
        end for
        if not found then exit end if
        printf(1,"%s = %s\n",{s,t})
        s = repeat(' ',length(s))
    end while
end procedure

reduce("exp(i*pi)+1")
Output:
exp(i*pi)+1 = cos(pi)+i*sin(pi)+1
            = -1+i*0+1
            = -1+0+1
            = -1+1
            = 0

Prolog

Symbolically manipulates Euler's identity until it can't be further reduced (and we get zero :)

% reduce() prints the intermediate results so that one can see Prolog "thinking."
%
reduce(A, C) :-
    simplify(A, B),
    (B = A -> C = A; io:format("= ~w~n", [B]), reduce(B, C)).

simplify(exp(i*X), cos(X) + i*sin(X)) :- !.

simplify(0 + A, A) :- !.
simplify(A + 0, A) :- !.
simplify(A + B, C) :-
    integer(A),
    integer(B), !,
    C is A + B.
simplify(A + B, C + D) :- !,
    simplify(A, C),
    simplify(B, D).

simplify(0 * _, 0) :- !.
simplify(_ * 0, 0) :- !.
simplify(1 * A, A) :- !.
simplify(A * 1, A) :- !.
simplify(A * B, C) :-
    integer(A),
    integer(B), !,
    C is A * B.
simplify(A * B, C * D) :- !,
    simplify(A, C),
    simplify(B, D).

simplify(cos(0),  1)  :- !.
simplify(sin(0),  0)  :- !.
simplify(cos(pi), -1) :- !.
simplify(sin(pi), 0)  :- !.

simplify(X, X).
Output:
?- reduce(exp(i*pi)+1, X).
= cos(pi)+i*sin(pi)+1
= -1+i*0+1
= -1+0+1
= -1+1
= 0
X = 0.

Python

>>> import math
>>> math.e ** (math.pi * 1j) + 1
1.2246467991473532e-16j

R

# lang R
exp(1i * pi) + 1
Output:
0+1.224606e-16i

Symbolically with the Ryacas package (on CRAN):

library(Ryacas)
as_r(yac_str("Exp(I * Pi) + 1"))
Output:
0

Racket

#lang racket
(+ (exp (* 0+i pi)) 1)
Output:
0.0+1.2246063538223773e-016i

Raku

(formerly Perl 6)

Works with: Rakudo version 2018.03

Implementing an "invisible times" operator (Unicode character (U+2062)) to more closely emulate the layout. Alas, Raku does not do symbolic calculations at this time and is limited to IEEE 754 floating point for transcendental and irrational number calculations.

e, i and π are all available as built-in constants in Raku.

sub infix:<⁢> is tighter(&infix:<**>) { $^a * $^b };

say 'e**i⁢π + 1 ≅ 0 : ', e**iπ + 10;
say 'Error: ', e**iπ + 1;
Output:
e**i⁢π + 1 ≅ 0 : True
Error: 0+1.2246467991473532e-16i

REXX

The   Euler formula   (or   Euler identity)   states:

eix   =   cos(x)   +   i sin(x)

Substituting   x   with     yields:

ei   =   cos()   +   i sin()

So, using this Rosetta Code task's version of Euler's identity:

ei                           +   1   =   0

then we have:

cos()   +   i sin()   +   1   =   0

So, if the left hand side is evaluated to zero, then Euler's identity is proven.


The REXX language doesn't have any trig or sqrt functions, so some stripped-down RYO versions are included here.

The   sqrt   function below supports complex roots.

Note that REXX uses decimal floating point, not binary.   REXX also uses a   guard   (decimal) digit when multiplying
and dividing,   which aids in increasing the precision.

This REXX program calculates the trigonometric functions   (sin and cos)   to around half of the number of decimal
digits that are used in defining the   pi   constant in the REXX program;   so the limiting factor for accuracy for the
trigonometric functions is based on the number of decimal digits (accuracy) of   pi   being defined within the REXX
program.

/*REXX program proves  Euler's  identity by showing that:      e^(i pi) + 1  ≡     0    */
numeric digits length( pi() )  -  length(.)      /*define pi;  set # dec. digs precision*/
        cosPI= fmt( cos(pi) )                    /*calculate the value of   cos(pi).    */
        sinPI= fmt( sin(pi) )                    /*    "      "    "    "   sin(pi).    */
say  '         cos(pi) = '  cosPI                /*display    "    "    "   cos(Pi).    */
say  '         sin(pi) = '  sinPI                /*   "       "    "    "   sin(Pi).    */
say                                              /*separate the wheat from the chaff.   */
     $= cosPI  +  mult( sqrt(-1), sinPI )  +  1  /*calc. product of sin(x) and sqrt(-1).*/
say  '    e^(i pi) + 1 = '  fmt($)    '    ' word("unproven proven",  ($=0)  +  1)
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
fmt:   procedure; parse arg x; x= format(x, , digits() %2, 0);   return left('', x>=0)x /1
mult:  procedure; parse arg a,b;       if a=0  | b=0  then return 0;            return a*b
pi:    pi= 3.1415926535897932384626433832795028841971693993751058209749445923;  return pi
cos:   procedure; parse arg x;  z= 1;  _= 1;   q= x*x;  i= -1;            return .sinCos()
sin:   procedure; parse arg x 1 z 1 _;         q= x*x;  i=  1;            return .sinCos()
.sinCos:   do k=2  by 2  until p=z;  p=z;  _= -_ * q/(k*(k+i));  z= z+_;  end;    return z
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt:  procedure; parse arg x;  if x=0  then return 0;  d=digits(); i=;             h= d+6
       numeric digits;  numeric form;   if x<0  then  do;  x= -x;   i= 'i';  end;   m.= 9
       parse value format(x, 2, 1, , 0)  'E0'   with   g  'E'  _  .;     g= g * .5'e'_ % 2
         do j=0  while h>9;      m.j= h;              h= h % 2   + 1;  end
         do k=j+5  to 0  by -1;  numeric digits m.k;  g= (g+x/g) *.5;  end;  return g || i
output   when using the internal default input:
         cos(pi) =  -1
         sin(pi) =   0

    e^(i pi) + 1 =   0      proven

Programming note:
To increase the decimal precision of the trigonometric functions past the current 500 decimal digits in the above REXX program,
use the following REXX assignment statement   (the author has a REXX program with 1,000,052 decimal digits of pi that can be
programmatically invoked with the requested number of decimal digits).

/*────────────────── 1,051  decimal digs of  pi. ──────────────────*/

pi=     3.14159265358979323846264338327950288419716939937510
pi= pi || 58209749445923078164062862089986280348253421170679
pi= pi || 82148086513282306647093844609550582231725359408128
pi= pi || 48111745028410270193852110555964462294895493038196
pi= pi || 44288109756659334461284756482337867831652712019091
pi= pi || 45648566923460348610454326648213393607260249141273
pi= pi || 72458700660631558817488152092096282925409171536436
pi= pi || 78925903600113305305488204665213841469519415116094
pi= pi || 33057270365759591953092186117381932611793105118548
pi= pi || 07446237996274956735188575272489122793818301194912
pi= pi || 98336733624406566430860213949463952247371907021798
pi= pi || 60943702770539217176293176752384674818467669405132
pi= pi || 00056812714526356082778577134275778960917363717872
pi= pi || 14684409012249534301465495853710507922796892589235
pi= pi || 42019956112129021960864034418159813629774771309960
pi= pi || 51870721134999999837297804995105973173281609631859
pi= pi || 50244594553469083026425223082533446850352619311881
pi= pi || 71010003137838752886587533208381420617177669147303
pi= pi || 59825349042875546873115956286388235378759375195778
pi= pi || 18577805321712268066130019278766111959092164201989
pi= pi || 38095257201065485863278865936153381827968230301952

RPL

Works with: Halcyon Calc version 4.2.7
'EXP(i*π)+1' →NUM ABS
Output:
1.22464679915E-16

Ruby

include Math

E ** (PI * 1i) + 1
# => (0.0+0.0i)

Rust

use std::f64::consts::PI;

extern crate num_complex;
use num_complex::Complex;

fn main() {
    println!("{:e}", Complex::new(0.0, PI).exp() + 1.0);
}
Output:
0e0+1.2246467991473532e-16i

Scala

This example makes use of Spire's numeric data types. Complex takes a type parameter determining the type of the coefficients of a + bi, and Real is Spire's exact (i.e. arbitrary precision) numeric data type.

import spire.math.{Complex, Real}

object Scratch extends App{
  //Declare values with friendly names to clean up the final expression
  val e = Complex[Real](Real.e, 0)
  val pi = Complex[Real](Real.pi, 0)
  val i = Complex[Real](0, 1)
  val one = Complex.one[Real]
  
  println(e.pow(pi*i) + one)
}
Output:
(0 + 0i)

Scheme

Works with: Chez Scheme
; A way to get pi.
(define pi (acos -1))

; Print the value of e^(i*pi) + 1 -- should be 0.
(printf "e^(i*pi) + 1 = ~a~%" (+ (exp (* +i pi)) 1))
Output:
e^(i*pi) + 1 = 0.0+1.2246467991473532e-16i
Works with: Chez Scheme

A higher precision test using series approximations to Pi and the Exp() function. The series are computed using exact rational numbers. This code converts the rational results into decimal representation.

; Procedure to compute factorial.

(define fact
  (lambda (n)
    (if (<= n 0)
      1
      (* n (fact (1- n))))))

; Use series to compute approximation to Pi (using N terms of series).
; (Uses the Newton / Euler Convergence Transformation.)

(define pi-series
  (lambda (n)
    (do ((k 0 (1+ k))
         (sum 0 (+ sum (/ (* (expt 2 k) (expt (fact k) 2)) (fact (1+ (* 2 k)))))))
        ((>= k n) (* 2 sum)))))

; Use series to compute approximation to exp(z) (using N terms of series).

(define exp-series
  (lambda (z n)
    (do ((k 0 (1+ k))
         (sum 0 (+ sum (/ (expt z k) (fact k)))))
        ((>= k n) sum))))

; Convert the given Rational number to a Decimal string.
; If opt contains an integer, show to that many places past the decimal regardless of repeating.
; If opt contains 'nopar, do not insert the parentheses indicating the repeating places.
; If opt contains 'plus, prefix positive numbers with plus ('+') sign.
; N.B.:  When number of decimals specified, this truncates instead of rounds.

(define rat->dec-str
  (lambda (rat . opt)
    (let* ((num (abs (numerator rat)))
           (den (abs (denominator rat)))
           (no-par (find (lambda (a) (eq? a 'nopar)) opt))
           (plus (find (lambda (a) (eq? a 'plus)) opt))
           (dec-lim (find integer? opt))
           (rep-inx #f)
           (rems-seen '())
           (int-part (format (cond ((< rat 0) "-~d") (plus "+~d") (else "~d")) (quotient num den)))
           (frc-list
             (cond
               ((zero? num)
                 '())
               (else
                 (let loop ((rem (modulo num den)) (decs 0))
                   (cond
                     ((or (<= rem 0) (and dec-lim (>= decs dec-lim)))
                       '())
                     ((and (not dec-lim) (assq rem rems-seen))
                       (set! rep-inx (cdr (assq rem rems-seen)))
                       '())
                     (else
                       (set! rems-seen (cons (cons rem decs) rems-seen))
                       (cons
                         (integer->char (+ (quotient (* 10 rem) den) (char->integer #\0)))
                         (loop (modulo (* 10 rem) den) (1+ decs))))))))))
      (when (and rep-inx (not no-par))
        (set! frc-list (append
                         (list-head frc-list rep-inx)
                         (list #\()
                         (list-tail frc-list rep-inx)
                         (list #\)))))
      (if (null? frc-list)
        int-part
        (format "~a.~a" int-part (list->string frc-list))))))

; Convert the given Rational Complex number to a Decimal string.
; If opt contains an integer, show to that many places past the decimal regardless of repeating.
; If opt contains 'nopar, do not insert the parentheses indicating the repeating places.
; If opt contains 'plus, prefix positive numbers with plus ('+') sign.
; N.B.:  When number of decimals specified, this truncates instead of rounds.

(define rat-cplx->dec-str
  (lambda (rat-cplx . opt)
    (let* ((real-dec-str (apply rat->dec-str (cons (real-part rat-cplx) opt)))
           (imag-dec-str (apply rat->dec-str (cons (imag-part rat-cplx) (cons 'plus opt)))))
      (format "~a~ai" real-dec-str imag-dec-str))))

; Print the value of e^(i*pi) + 1 -- should be 0.
; (Computed using the series defined above.)

(let*
    ((pi (pi-series 222))
     (e-pi-i (exp-series (* pi +i) 222))
     (euler-id (+ e-pi-i 1)))
  (printf "e^(i*pi) + 1 = ~a~%" (rat-cplx->dec-str euler-id 70)))
Output:
e^(i*pi) + 1 =
  0.0000000000000000000000000000000000000000000000000000000000000000000000
 +0.0000000000000000000000000000000000000000000000000000000000000000000351i

Sidef

say ('e**i⁢π + 1 ≅ 0 : ', Num.e**Num.pi.i + 1  0)
say ('Error: ', Num.e**Num.pi.i + 1)
Output:
e**i⁢π + 1 ≅ 0 : true
Error: -2.42661922624586582047028764157944836122122513308e-58i

Tcl

Using tcllib

# Set up complex sandbox (since we're doing a star import)
namespace eval complex_ns {
    package require math::complexnumbers
    namespace import ::math::complexnumbers::*

    set pi [expr {acos(-1)}]

    set r [+ [exp [complex 0 $pi]] [complex 1 0]]
    puts "e**(pi*i) = [real $r]+[imag $r]i"
}
Output:
e**(pi*i) = 0.0+1.2246467991473532e-16i

Using VecTcl

package require vectcl
namespace import vectcl::vexpr

set ans [vexpr {pi=acos(-1); exp(pi*1i) + 1}]
puts "e**(pi*i) = $ans"
Output:
e**(pi*i) = 0.0+1.2246063538223773e-16i

Wren

Library: Wren-complex
import "./complex" for Complex

System.print((Complex.new(0, Num.pi).exp + Complex.one).toString)
Output:
0 + 1.2246467991474e-16i

zkl

var [const] GSL=Import("zklGSL");	// libGSL (GNU Scientific Library)
Z,pi,e := GSL.Z, (0.0).pi, (0.0).e;

println("e^(\u03c0i) + 1 = %s \u2245 0".fmt( Z(e).pow(Z(0,1)*pi) + 1 ));
println("TMI: ",(Z(e).pow(Z(0,1)*pi) + 1 ).format(0,25,"g"));
Output:
e^(πi) + 1 = (0.00+0.00i) ≅ 0
TMI: (0+1.224646799147353207173764e-16i)