Arithmetic/Complex: Difference between revisions

Content added Content deleted
(Added Hare)
m (syntax highlighting fixup automation)
Line 29: Line 29:
{{trans|Python}}
{{trans|Python}}


<lang 11l>V z1 = 1.5 + 3i
<syntaxhighlight lang=11l>V z1 = 1.5 + 3i
V z2 = 1.5 + 1.5i
V z2 = 1.5 + 1.5i
print(z1 + z2)
print(z1 + z2)
Line 40: Line 40:
print(z1 ^ z2)
print(z1 ^ z2)
print(z1.real)
print(z1.real)
print(z1.imag)</lang>
print(z1.imag)</syntaxhighlight>


{{out}}
{{out}}
Line 58: Line 58:
=={{header|Action!}}==
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
<lang Action!>INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
<syntaxhighlight lang=Action!>INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit


DEFINE R_="+0"
DEFINE R_="+0"
Line 192: Line 192:
ComplexConj(y,res)
ComplexConj(y,res)
PrintComplexXY(y,res," conj")
PrintComplexXY(y,res," conj")
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Complex.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Complex.png Screenshot from Atari 8-bit computer]
Line 206: Line 206:


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>with Ada.Numerics.Generic_Complex_Types;
<syntaxhighlight lang=ada>with Ada.Numerics.Generic_Complex_Types;
with Ada.Text_IO.Complex_IO;
with Ada.Text_IO.Complex_IO;


Line 252: Line 252:
Put("Conjugate(-A) = ");
Put("Conjugate(-A) = ");
C := Conjugate (C); Put(C);
C := Conjugate (C); Put(C);
end Complex_Operations;</lang>
end Complex_Operations;</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 259: Line 259:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
<lang algol68>main:(
<syntaxhighlight lang=algol68>main:(
FORMAT compl fmt = $g(-7,5)"⊥"g(-7,5)$;
FORMAT compl fmt = $g(-7,5)"⊥"g(-7,5)$;
Line 285: Line 285:
);
);
compl operations
compl operations
)</lang>
)</syntaxhighlight>


{{out}}<pre>
{{out}}<pre>
Line 298: Line 298:
=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
Complex is a built-in type in Algol W.
Complex is a built-in type in Algol W.
<lang algolw>begin
<syntaxhighlight lang=algolw>begin
% show some complex arithmetic %
% show some complex arithmetic %
% returns c + d, using the builtin complex + operator %
% returns c + d, using the builtin complex + operator %
Line 322: Line 322:
write( "1/c : ", cInv( c ) );
write( "1/c : ", cInv( c ) );
write( "conj c : ", cConj( c ) )
write( "conj c : ", cConj( c ) )
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 346: Line 346:
-x ⍝negation
-x ⍝negation
¯1J¯1
¯1J¯1
</syntaxhighlight>
</lang>


=={{header|App Inventor}}==
=={{header|App Inventor}}==
Line 355: Line 355:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>a: to :complex [1 1]
<syntaxhighlight lang=rebol>a: to :complex [1 1]
b: to :complex @[pi 1.2]
b: to :complex @[pi 1.2]


Line 365: Line 365:
print ["1 / a:" 1 / a]
print ["1 / a:" 1 / a]
print ["neg a:" neg a]
print ["neg a:" neg a]
print ["conj a:" conj a]</lang>
print ["conj a:" conj a]</syntaxhighlight>


{{out}}
{{out}}
Line 379: Line 379:
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276431.html#276431 forum]
contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276431.html#276431 forum]
<lang AutoHotkey>Cset(C,1,1)
<syntaxhighlight lang=AutoHotkey>Cset(C,1,1)
MsgBox % Cstr(C) ; 1 + i*1
MsgBox % Cstr(C) ; 1 + i*1
Cneg(C,C)
Cneg(C,C)
Line 425: Line 425:
NumPut( Cre(A)/d,C,0,"double")
NumPut( Cre(A)/d,C,0,"double")
NumPut(-Cim(A)/d,C,8,"double")
NumPut(-Cim(A)/d,C,8,"double")
}</lang>
}</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
contributed by af
contributed by af
<lang awk># simulate a struct using associative arrays
<syntaxhighlight lang=awk># simulate a struct using associative arrays
function complex(arr, re, im) {
function complex(arr, re, im) {
arr["re"] = re
arr["re"] = re
Line 484: Line 484:
mult(i, i, i)
mult(i, i, i)
printComplex(i)
printComplex(i)
}</lang>
}</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
{{works with|QuickBasic|4.5}}
<lang qbasic>TYPE complex
<syntaxhighlight lang=qbasic>TYPE complex
real AS DOUBLE
real AS DOUBLE
imag AS DOUBLE
imag AS DOUBLE
Line 564: Line 564:
c.imag = a.imag - b.imag
c.imag = a.imag - b.imag
END SUB
END SUB
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Siendo x = 1+ 3i
<pre>Siendo x = 1+ 3i
Line 579: Line 579:
=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> DIM Complex{r, i}
<syntaxhighlight lang=bbcbasic> DIM Complex{r, i}
DIM a{} = Complex{} : a.r = 1.0 : a.i = 1.0
DIM a{} = Complex{} : a.r = 1.0 : a.i = 1.0
Line 618: Line 618:
DEF FNcomplexshow(src{})
DEF FNcomplexshow(src{})
IF src.i >= 0 THEN = STR$(src.r) + " + " +STR$(src.i) + "i"
IF src.i >= 0 THEN = STR$(src.r) + " + " +STR$(src.i) + "i"
= STR$(src.r) + " - " + STR$(-src.i) + "i"</lang>
= STR$(src.r) + " - " + STR$(-src.i) + "i"</syntaxhighlight>
{{out}}
{{out}}
<pre>Result of addition is 4.14159265 + 2.2i
<pre>Result of addition is 4.14159265 + 2.2i
Line 627: Line 627:
=={{header|Bracmat}}==
=={{header|Bracmat}}==
Bracmat recognizes the symbol <code>i</code> as the square root of <code>-1</code>. The results of the functions below are not necessarily of the form <code>a+b*i</code>, but as the last example shows, Bracmat nevertheless can work out that two different representations of the same mathematical object, when subtracted from each other, give zero. You may wonder why in the functions <code>multiply</code> and <code>negate</code> there are terms <code>1</code> and <code>-1</code>. These terms are a trick to force Bracmat to expand the products. As it is more costly to factorize a sum than to expand a product into a sum, Bracmat retains isolated products. However, when in combination with a non-zero term, the product is expanded.
Bracmat recognizes the symbol <code>i</code> as the square root of <code>-1</code>. The results of the functions below are not necessarily of the form <code>a+b*i</code>, but as the last example shows, Bracmat nevertheless can work out that two different representations of the same mathematical object, when subtracted from each other, give zero. You may wonder why in the functions <code>multiply</code> and <code>negate</code> there are terms <code>1</code> and <code>-1</code>. These terms are a trick to force Bracmat to expand the products. As it is more costly to factorize a sum than to expand a product into a sum, Bracmat retains isolated products. However, when in combination with a non-zero term, the product is expanded.
<lang bracmat> (add=a b.!arg:(?a,?b)&!a+!b)
<syntaxhighlight lang=bracmat> (add=a b.!arg:(?a,?b)&!a+!b)
& ( multiply
& ( multiply
= a b.!arg:(?a,?b)&1+!a*!b+-1
= a b.!arg:(?a,?b)&1+!a*!b+-1
Line 654: Line 654:
& out
& out
$ ("sin$x minus conjugate sin$x =" sin$x+negate$(conjugate$(sin$x)))
$ ("sin$x minus conjugate sin$x =" sin$x+negate$(conjugate$(sin$x)))
& done;</lang>
& done;</syntaxhighlight>
{{out}}
{{out}}
<pre>(a+i*b)+(a+i*b) = 2*a+2*i*b
<pre>(a+i*b)+(a+i*b) = 2*a+2*i*b
Line 669: Line 669:
{{works with|C99}}
{{works with|C99}}
The more recent [[C99]] standard has built-in complex number primitive types, which can be declared with float, double, or long double precision. To use these types and their associated library functions, you must include the <complex.h> header. (Note: this is a ''different'' header than the <complex> templates that are defined by [[C++]].) [http://www.opengroup.org/onlinepubs/009695399/basedefs/complex.h.html] [http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.vacpp7a.doc/language/ref/clrc03complex_types.htm]
The more recent [[C99]] standard has built-in complex number primitive types, which can be declared with float, double, or long double precision. To use these types and their associated library functions, you must include the <complex.h> header. (Note: this is a ''different'' header than the <complex> templates that are defined by [[C++]].) [http://www.opengroup.org/onlinepubs/009695399/basedefs/complex.h.html] [http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.vacpp7a.doc/language/ref/clrc03complex_types.htm]
<lang c>#include <complex.h>
<syntaxhighlight lang=c>#include <complex.h>
#include <stdio.h>
#include <stdio.h>


Line 700: Line 700:
c = conj(a);
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
printf("\nconj a="); cprint(c); printf("\n");
}</lang>
}</syntaxhighlight>


{{works with|C89}}
{{works with|C89}}
User-defined type:
User-defined type:
<lang c>typedef struct{
<syntaxhighlight lang=c>typedef struct{
double real;
double real;
double imag;
double imag;
Line 764: Line 764:
printf("\n-a="); put(neg(a));
printf("\n-a="); put(neg(a));
printf("\nconj a="); put(conj(a)); printf("\n");
printf("\nconj a="); put(conj(a)); printf("\n");
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
{{works with|C sharp|C#|4.0}}
{{works with|C sharp|C#|4.0}}
<lang csharp>namespace RosettaCode.Arithmetic.Complex
<syntaxhighlight lang=csharp>namespace RosettaCode.Arithmetic.Complex
{
{
using System;
using System;
Line 784: Line 784:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{works with|C sharp|C#|1.2}}
{{works with|C sharp|C#|1.2}}
<lang csharp>using System;
<syntaxhighlight lang=csharp>using System;


public struct ComplexNumber
public struct ComplexNumber
Line 990: Line 990:
Console.WriteLine(ComplexMath.Power(j, 0) == 1.0);
Console.WriteLine(ComplexMath.Power(j, 0) == 1.0);
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang=cpp>#include <iostream>
#include <complex>
#include <complex>
using std::complex;
using std::complex;
Line 1,011: Line 1,011:
// conjugate
// conjugate
std::cout << std::conj(a) << std::endl;
std::cout << std::conj(a) << std::endl;
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
Line 1,017: Line 1,017:
Therefore, we use defrecord and the multimethods in
Therefore, we use defrecord and the multimethods in
clojure.algo.generic.arithmetic to make a Complex number type.
clojure.algo.generic.arithmetic to make a Complex number type.
<lang clojure>(ns rosettacode.arithmetic.cmplx
<syntaxhighlight lang=clojure>(ns rosettacode.arithmetic.cmplx
(:require [clojure.algo.generic.arithmetic :as ga])
(:require [clojure.algo.generic.arithmetic :as ga])
(:import [java.lang Number]))
(:import [java.lang Number]))
Line 1,054: Line 1,054:
(let [m (+ (* r r) (* i i))]
(let [m (+ (* r r) (* i i))]
(->Complex (/ r m) (- (/ i m)))))
(->Complex (/ r m) (- (/ i m)))))
</syntaxhighlight>
</lang>


=={{header|COBOL}}==
=={{header|COBOL}}==
Line 1,061: Line 1,061:
===.NET Complex class===
===.NET Complex class===
{{trans|C#}}
{{trans|C#}}
<lang cobol> $SET SOURCEFORMAT "FREE"
<syntaxhighlight lang=cobol> $SET SOURCEFORMAT "FREE"
$SET ILUSING "System"
$SET ILUSING "System"
$SET ILUSING "System.Numerics"
$SET ILUSING "System.Numerics"
Line 1,074: Line 1,074:
end-perform
end-perform
end method.
end method.
end class.</lang>
end class.</syntaxhighlight>


===Implementation===
===Implementation===
<lang cobol> $SET SOURCEFORMAT "FREE"
<syntaxhighlight lang=cobol> $SET SOURCEFORMAT "FREE"
class-id Prog.
class-id Prog.
method-id. Main static.
method-id. Main static.
Line 1,174: Line 1,174:
end operator.
end operator.


end class.</lang>
end class.</syntaxhighlight>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<lang coffeescript>
<syntaxhighlight lang=coffeescript>
# create an immutable Complex type
# create an immutable Complex type
class Complex
class Complex
Line 1,238: Line 1,238:
quotient = product.times inverse
quotient = product.times inverse
console.log "(#{product}) / (#{b}) = #{quotient}"
console.log "(#{product}) / (#{b}) = #{quotient}"
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,255: Line 1,255:
Complex numbers are a built-in numeric type in Common Lisp. The literal syntax for a complex number is <tt>#C(<var>real</var> <var>imaginary</var>)</tt>. The components of a complex number may be integers, ratios, or floating-point. Arithmetic operations automatically return complex (or real) numbers when appropriate:
Complex numbers are a built-in numeric type in Common Lisp. The literal syntax for a complex number is <tt>#C(<var>real</var> <var>imaginary</var>)</tt>. The components of a complex number may be integers, ratios, or floating-point. Arithmetic operations automatically return complex (or real) numbers when appropriate:


<lang lisp>> (sqrt -1)
<syntaxhighlight lang=lisp>> (sqrt -1)
#C(0.0 1.0)
#C(0.0 1.0)


> (expt #c(0 1) 2)
> (expt #c(0 1) 2)
-1</lang>
-1</syntaxhighlight>


Here are some arithmetic operations on complex numbers:
Here are some arithmetic operations on complex numbers:


<lang lisp>> (+ #c(0 1) #c(1 0))
<syntaxhighlight lang=lisp>> (+ #c(0 1) #c(1 0))
#C(1 1)
#C(1 1)


Line 1,279: Line 1,279:


> (conjugate #c(1 1))
> (conjugate #c(1 1))
#C(1 -1)</lang>
#C(1 -1)</syntaxhighlight>


Complex numbers can be constructed from real and imaginary parts using the <tt>complex</tt> function, and taken apart using the <tt>realpart</tt> and <tt>imagpart</tt> functions.
Complex numbers can be constructed from real and imaginary parts using the <tt>complex</tt> function, and taken apart using the <tt>realpart</tt> and <tt>imagpart</tt> functions.


<lang lisp>> (complex 64 (/ 3 4))
<syntaxhighlight lang=lisp>> (complex 64 (/ 3 4))
#C(64 3/4)
#C(64 3/4)


Line 1,290: Line 1,290:


> (imagpart (complex 0 pi))
> (imagpart (complex 0 pi))
3.141592653589793d0</lang>
3.141592653589793d0</syntaxhighlight>


=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
BlackBox Component Builder
BlackBox Component Builder
<lang oberon2>
<syntaxhighlight lang=oberon2>
MODULE Complex;
MODULE Complex;
IMPORT StdLog;
IMPORT StdLog;
Line 1,381: Line 1,381:


END Complex.
END Complex.
</syntaxhighlight>
</lang>
Execute: ^Q Complex.Do<br/>
Execute: ^Q Complex.Do<br/>
{{out}}
{{out}}
Line 1,397: Line 1,397:
=={{header|D}}==
=={{header|D}}==
Built-in complex numbers are now deprecated in D, to simplify the language.
Built-in complex numbers are now deprecated in D, to simplify the language.
<lang d>import std.stdio, std.complex;
<syntaxhighlight lang=d>import std.stdio, std.complex;


void main() {
void main() {
Line 1,407: Line 1,407:
writeln(1.0 / x); // inversion
writeln(1.0 / x); // inversion
writeln(-x); // negation
writeln(-x); // negation
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>4.14159+2.2i
<pre>4.14159+2.2i
Line 1,415: Line 1,415:


=={{header|Dart}}==
=={{header|Dart}}==
<lang dart>
<syntaxhighlight lang=dart>


class complex {
class complex {
Line 1,467: Line 1,467:


}
}
</syntaxhighlight>
</lang>
=={{header|Delphi}}==
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.SysUtils}}
{{libheader| System.VarCmplx}}
{{libheader| System.VarCmplx}}
<lang Delphi>
<syntaxhighlight lang=Delphi>
program Arithmetic_Complex;
program Arithmetic_Complex;


Line 1,498: Line 1,498:


Readln;
Readln;
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>(5 + 3i) + (0,5 + 6i) = 5,5 + 9i
<pre>(5 + 3i) + (0,5 + 6i) = 5,5 + 9i
Line 1,507: Line 1,507:
=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
Complex numbers are part of the language. No special library is needed.
Complex numbers are part of the language. No special library is needed.
<lang lisp>
<syntaxhighlight lang=lisp>
(define a 42+666i) → a
(define a 42+666i) → a
(define b 1+i) → b
(define b 1+i) → b
Line 1,518: Line 1,518:
(magnitude b) → 1.4142135623730951 ; = sqrt(2)
(magnitude b) → 1.4142135623730951 ; = sqrt(2)
(exp (* I PI)) → -1+0i ; Euler = e^(I*PI) = -1
(exp (* I PI)) → -1+0i ; Euler = e^(I*PI) = -1
</syntaxhighlight>
</lang>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>defmodule Complex do
<syntaxhighlight lang=elixir>defmodule Complex do
import Kernel, except: [abs: 1, div: 2]
import Kernel, except: [abs: 1, div: 2]
Line 1,605: Line 1,605:
end
end


Complex.task</lang>
Complex.task</syntaxhighlight>


{{out}}
{{out}}
Line 1,622: Line 1,622:


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang Erlang>%% Task: Complex Arithmetic
<syntaxhighlight lang=Erlang>%% Task: Complex Arithmetic
%% Author: Abhay Jain
%% Author: Abhay Jain


Line 1,679: Line 1,679:
true ->
true ->
io:format("Ans = ~p+~pi~n", [A#complex.real, A#complex.img])
io:format("Ans = ~p+~pi~n", [A#complex.real, A#complex.img])
end. </lang>
end. </syntaxhighlight>
{{out}}
{{out}}
<lang Erlang>Ans = 6+5i
<syntaxhighlight lang=Erlang>Ans = 6+5i
Ans = -1+17i
Ans = -1+17i
Ans = -1-3i
Ans = -1-3i
Ans = 0.1-0.3i
Ans = 0.1-0.3i
Ans = 1-3i</lang>
Ans = 1-3i</syntaxhighlight>


=={{header|ERRE}}==
=={{header|ERRE}}==
Line 1,737: Line 1,737:
PRINT(Z.REAL#;" + ";Z.IMAG#;"i")
PRINT(Z.REAL#;" + ";Z.IMAG#;"i")
END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>
Note: Adapted from QuickBasic source code
Note: Adapted from QuickBasic source code
{{out}}
{{out}}
Line 1,747: Line 1,747:
=={{header|Euler Math Toolbox}}==
=={{header|Euler Math Toolbox}}==


<lang Euler Math Toolbox>
<syntaxhighlight lang=Euler Math Toolbox>
>a=1+4i; b=5-3i;
>a=1+4i; b=5-3i;
>a+b
>a+b
Line 1,761: Line 1,761:
>conj(a)
>conj(a)
1-4i
1-4i
</syntaxhighlight>
</lang>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>constant REAL = 1, IMAG = 2
<syntaxhighlight lang=euphoria>constant REAL = 1, IMAG = 2
type complex(sequence s)
type complex(sequence s)
return length(s) = 2 and atom(s[REAL]) and atom(s[IMAG])
return length(s) = 2 and atom(s[REAL]) and atom(s[IMAG])
Line 1,821: Line 1,821:
printf(1,"a*b = %s\n",{scomplex(mult(a,b))})
printf(1,"a*b = %s\n",{scomplex(mult(a,b))})
printf(1,"1/a = %s\n",{scomplex(inv(a))})
printf(1,"1/a = %s\n",{scomplex(inv(a))})
printf(1,"-a = %s\n",{scomplex(neg(a))})</lang>
printf(1,"-a = %s\n",{scomplex(neg(a))})</syntaxhighlight>


{{out}}
{{out}}
Line 1,835: Line 1,835:


C1:
C1:
<lang excel>
<syntaxhighlight lang=excel>
=IMSUM(A1;B1)
=IMSUM(A1;B1)
</syntaxhighlight>
</lang>


D1:
D1:
<lang excel>
<syntaxhighlight lang=excel>
=IMPRODUCT(A1;B1)
=IMPRODUCT(A1;B1)
</syntaxhighlight>
</lang>


E1:
E1:
<lang excel>
<syntaxhighlight lang=excel>
=IMSUB(0;D1)
=IMSUB(0;D1)
</syntaxhighlight>
</lang>


F1:
F1:
<lang excel>
<syntaxhighlight lang=excel>
=IMDIV(1;E28)
=IMDIV(1;E28)
</syntaxhighlight>
</lang>


G1:
G1:
<lang excel>
<syntaxhighlight lang=excel>
=IMCONJUGATE(C28)
=IMCONJUGATE(C28)
</syntaxhighlight>
</lang>


E1 will have the negation of D1's value
E1 will have the negation of D1's value
Line 1,863: Line 1,863:
<lang>
<lang>
1+2i 3+5i 4+7i -7+11i 7-11i 0,0411764705882353+0,0647058823529412i 4-7i
1+2i 3+5i 4+7i -7+11i 7-11i 0,0411764705882353+0,0647058823529412i 4-7i
</syntaxhighlight>
</lang>


=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
Entered into an interactive session to show the results:
Entered into an interactive session to show the results:
<lang fsharp>
<syntaxhighlight lang=fsharp>
> open Microsoft.FSharp.Math;;
> open Microsoft.FSharp.Math;;


Line 1,913: Line 1,913:
i = -1.0;
i = -1.0;
r = -1.0;}
r = -1.0;}
</syntaxhighlight>
</lang>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: combinators kernel math math.functions prettyprint ;
<syntaxhighlight lang=factor>USING: combinators kernel math math.functions prettyprint ;


C{ 1 2 } C{ 0.9 -2.78 } {
C{ 1 2 } C{ 0.9 -2.78 } {
Line 1,933: Line 1,933:
[ log . ] ! natural logarithm
[ log . ] ! natural logarithm
[ sqrt . ] ! square root
[ sqrt . ] ! square root
} cleave</lang>
} cleave</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
{{libheader|Forth Scientific Library}}
{{libheader|Forth Scientific Library}}
Historically, there was no standard syntax or mechanism for complex numbers and several implementations suitable for different uses were provided. However later a wordset ''was'' standardised as "Algorithm #60".
Historically, there was no standard syntax or mechanism for complex numbers and several implementations suitable for different uses were provided. However later a wordset ''was'' standardised as "Algorithm #60".
<lang forth>S" fsl-util.fs" REQUIRED
<syntaxhighlight lang=forth>S" fsl-util.fs" REQUIRED
S" complex.fs" REQUIRED
S" complex.fs" REQUIRED


Line 1,950: Line 1,950:
1e 0e zconstant 1+0i
1e 0e zconstant 1+0i
1+0i x z@ z/ z.
1+0i x z@ z/ z.
x z@ znegate z.</lang>
x z@ znegate z.</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
In ANSI FORTRAN 66 or later, COMPLEX is a built-in data type with full access to intrinsic arithmetic operations. Putting each native operation in a function is horribly inefficient, so I will simply demonstrate the operations. This example shows usage for Fortran 90 or later:
In ANSI FORTRAN 66 or later, COMPLEX is a built-in data type with full access to intrinsic arithmetic operations. Putting each native operation in a function is horribly inefficient, so I will simply demonstrate the operations. This example shows usage for Fortran 90 or later:
<lang fortran>program cdemo
<syntaxhighlight lang=fortran>program cdemo
complex :: a = (5,3), b = (0.5, 6.0) ! complex initializer
complex :: a = (5,3), b = (0.5, 6.0) ! complex initializer
complex :: absum, abprod, aneg, ainv
complex :: absum, abprod, aneg, ainv
Line 1,962: Line 1,962:
aneg = -a
aneg = -a
ainv = 1.0 / a
ainv = 1.0 / a
end program cdemo</lang>
end program cdemo</syntaxhighlight>


And, although you did not ask, here are demonstrations of some other common complex number operations
And, although you did not ask, here are demonstrations of some other common complex number operations
<lang fortran>program cdemo2
<syntaxhighlight lang=fortran>program cdemo2
complex :: a = (5,3), b = (0.5, 6) ! complex initializer
complex :: a = (5,3), b = (0.5, 6) ! complex initializer
real, parameter :: pi = 3.141592653589793 ! The constant "pi"
real, parameter :: pi = 3.141592653589793 ! The constant "pi"
Line 1,992: Line 1,992:
! useful for FFT calculations, among other things
! useful for FFT calculations, among other things
unit_circle = exp(2*i*pi/n * (/ (j, j=0, n-1) /) )
unit_circle = exp(2*i*pi/n * (/ (j, j=0, n-1) /) )
end program cdemo2</lang>
end program cdemo2</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang=freebasic>' FB 1.05.0 Win64


Type Complex
Type Complex
Line 2,059: Line 2,059:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 2,076: Line 2,076:
=={{header|Free Pascal}}==
=={{header|Free Pascal}}==
FreePascal has a complex units. Example of usage:
FreePascal has a complex units. Example of usage:
<lang Pascal>Program ComplexDemo;
<syntaxhighlight lang=Pascal>Program ComplexDemo;


uses
uses
Line 2,104: Line 2,104:
writeln ('conj(5 + i3): ', acong.re:3:1, ' + i', acong.im:3:1);
writeln ('conj(5 + i3): ', acong.re:3:1, ' + i', acong.im:3:1);
end.
end.
</syntaxhighlight>
</lang>


=={{header|Frink}}==
=={{header|Frink}}==
Frink's operations handle complex numbers naturally. The real and imaginary parts of complex numbers can be arbitrary-sized integers, arbitrary-sized rational numbers, or arbitrary-precision floating-point numbers.
Frink's operations handle complex numbers naturally. The real and imaginary parts of complex numbers can be arbitrary-sized integers, arbitrary-sized rational numbers, or arbitrary-precision floating-point numbers.
<lang frink>
<syntaxhighlight lang=frink>
add[x,y] := x + y
add[x,y] := x + y
multiply[x,y] := x * y
multiply[x,y] := x * y
Line 2,122: Line 2,122:
println["1/$a = " + invert[a]]
println["1/$a = " + invert[a]]
println["conjugate[$a] = " + conjugate[a]]
println["conjugate[$a] = " + conjugate[a]]
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,135: Line 2,135:
=={{header|Futhark}}==
=={{header|Futhark}}==
{{incorrect|Futhark|Futhark's syntax has changed, so "fun" should be "let"}}
{{incorrect|Futhark|Futhark's syntax has changed, so "fun" should be "let"}}
<lang Futhark>
<syntaxhighlight lang=Futhark>
type complex = (f64,f64)
type complex = (f64,f64)


Line 2,163: Line 2,163:
else if o == 3 then complexNeg a
else if o == 3 then complexNeg a
else complexConj a
else complexConj a
</syntaxhighlight>
</lang>


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap># GAP knows gaussian integers, gaussian rationals (i.e. Q[i]), and cyclotomic fields. Here are some examples.
<syntaxhighlight lang=gap># GAP knows gaussian integers, gaussian rationals (i.e. Q[i]), and cyclotomic fields. Here are some examples.
# E(n) is an nth primitive root of 1
# E(n) is an nth primitive root of 1
i := Sqrt(-1);
i := Sqrt(-1);
Line 2,184: Line 2,184:
# true
# true
Sqrt(-3) in Cyclotomics;
Sqrt(-3) in Cyclotomics;
# true</lang>
# true</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
Go has complex numbers built in, with the complex conjugate in the standard library.
Go has complex numbers built in, with the complex conjugate in the standard library.
<lang go>package main
<syntaxhighlight lang=go>package main


import (
import (
Line 2,205: Line 2,205:
fmt.Println("1 / a: ", 1/a)
fmt.Println("1 / a: ", 1/a)
fmt.Println("a̅: ", cmplx.Conj(a))
fmt.Println("a̅: ", cmplx.Conj(a))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,219: Line 2,219:
=={{header|Groovy}}==
=={{header|Groovy}}==
Groovy does not provide any built-in facility for complex arithmetic. However, it does support arithmetic operator overloading. Thus it is not too hard to build a fairly robust, complete, and intuitive complex number class, such as the following:
Groovy does not provide any built-in facility for complex arithmetic. However, it does support arithmetic operator overloading. Thus it is not too hard to build a fairly robust, complete, and intuitive complex number class, such as the following:
<lang groovy>class Complex {
<syntaxhighlight lang=groovy>class Complex {
final Number real, imag
final Number real, imag
Line 2,319: Line 2,319:
: realPart + (imag > 0 ? " + " : " - ") + imagPart
: realPart + (imag > 0 ? " + " : " - ") + imagPart
}
}
}</lang>
}</syntaxhighlight>


The following ''ComplexCategory'' class allows for modification of regular ''Number'' behavior when interacting with ''Complex''.
The following ''ComplexCategory'' class allows for modification of regular ''Number'' behavior when interacting with ''Complex''.
<lang groovy>import org.codehaus.groovy.runtime.DefaultGroovyMethods
<syntaxhighlight lang=groovy>import org.codehaus.groovy.runtime.DefaultGroovyMethods
class ComplexCategory {
class ComplexCategory {
Line 2,338: Line 2,338:
: DefaultGroovyMethods.asType(a, type)
: DefaultGroovyMethods.asType(a, type)
}
}
}</lang>
}</syntaxhighlight>
Notice also that this solution takes liberal advantage of Groovy's full Unicode support, including support for non-English alphabets used in identifiers.
Notice also that this solution takes liberal advantage of Groovy's full Unicode support, including support for non-English alphabets used in identifiers.


Test Program (mixes the ComplexCategory methods into the Number class):
Test Program (mixes the ComplexCategory methods into the Number class):
<lang groovy>import static Complex.*
<syntaxhighlight lang=groovy>import static Complex.*
Number.metaClass.mixin ComplexCategory
Number.metaClass.mixin ComplexCategory
Line 2,405: Line 2,405:
println " == 10*0.5 + i*10*√(3/4) == " + fromPolar1
println " == 10*0.5 + i*10*√(3/4) == " + fromPolar1
println "ρ*exp(i*θ) == ${ρ}*exp(i*π/${n}) == " + fromPolar2
println "ρ*exp(i*θ) == ${ρ}*exp(i*π/${n}) == " + fromPolar2
assert (fromPolar1 - fromPolar2).abs < ε</lang>
assert (fromPolar1 - fromPolar2).abs < ε</syntaxhighlight>


{{out}}
{{out}}
Line 2,440: Line 2,440:


=={{header|Hare}}==
=={{header|Hare}}==
<lang hare>use fmt;
<syntaxhighlight lang=hare>use fmt;
use math::complex::{c128,addc128,mulc128,divc128,negc128,conjc128};
use math::complex::{c128,addc128,mulc128,divc128,negc128,conjc128};


Line 2,462: Line 2,462:
let (re, im) = conjc128(x);
let (re, im) = conjc128(x);
fmt::printfln("{} + {}i", re, im)!;
fmt::printfln("{} + {}i", re, im)!;
};</lang>
};</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
Line 2,469: Line 2,469:
have ''Complex Integer'' for the Gaussian Integers, ''Complex Float'', ''Complex Double'', etc. The operations are just the usual overloaded numeric operations.
have ''Complex Integer'' for the Gaussian Integers, ''Complex Float'', ''Complex Double'', etc. The operations are just the usual overloaded numeric operations.


<lang haskell>import Data.Complex
<syntaxhighlight lang=haskell>import Data.Complex


main = do
main = do
Line 2,482: Line 2,482:
putStrLn $ "Negate: " ++ show (-a)
putStrLn $ "Negate: " ++ show (-a)
putStrLn $ "Inverse: " ++ show (recip a)
putStrLn $ "Inverse: " ++ show (recip a)
putStrLn $ "Conjugate:" ++ show (conjugate a)</lang>
putStrLn $ "Conjugate:" ++ show (conjugate a)</syntaxhighlight>


{{out}}
{{out}}
Line 2,497: Line 2,497:
{{improve|Unicon|This could be better implemented as an object i n Unicon. Note, however, that Unicon doesn't allow for operator overloading at the current time.}}
{{improve|Unicon|This could be better implemented as an object i n Unicon. Note, however, that Unicon doesn't allow for operator overloading at the current time.}}
Icon doesn't provide native support for complex numbers. Support is included in the IPL.
Icon doesn't provide native support for complex numbers. Support is included in the IPL.
<lang Icon>procedure main()
<syntaxhighlight lang=Icon>procedure main()


SetupComplex()
SetupComplex()
Line 2,518: Line 2,518:
write("abs(a) := ", cpxabs(a))
write("abs(a) := ", cpxabs(a))
write("neg(1) := ", cpxstr(cpxneg(1)))
write("neg(1) := ", cpxstr(cpxneg(1)))
end</lang>
end</syntaxhighlight>
Icon doesn't allow for operator overloading but procedures can be overloaded as was done here to allow 'complex' to behave more robustly.
Icon doesn't allow for operator overloading but procedures can be overloaded as was done here to allow 'complex' to behave more robustly.


{{libheader|Icon Programming Library}}
{{libheader|Icon Programming Library}}
[http://www.cs.arizona.edu/icon/library/src/procs/complex.icn provides complex number support] supplemented by the code below.
[http://www.cs.arizona.edu/icon/library/src/procs/complex.icn provides complex number support] supplemented by the code below.
<lang Icon>
<syntaxhighlight lang=Icon>
link complex # for complex number support
link complex # for complex number support


Line 2,550: Line 2,550:
denom := z.rpart ^ 2 + z.ipart ^ 2
denom := z.rpart ^ 2 + z.ipart ^ 2
return complex(z.rpart / denom, z.ipart / denom)
return complex(z.rpart / denom, z.ipart / denom)
end</lang>
end</syntaxhighlight>
To take full advantage of the overloaded 'complex' procedure,
To take full advantage of the overloaded 'complex' procedure,
the other cpxxxx procedures would need to be rewritten or overloaded.
the other cpxxxx procedures would need to be rewritten or overloaded.
Line 2,576: Line 2,576:
<tt>complex</tt> (and <tt>dcomplex</tt> for double-precision) is a built-in data type in IDL:
<tt>complex</tt> (and <tt>dcomplex</tt> for double-precision) is a built-in data type in IDL:


<lang idl>x=complex(1,1)
<syntaxhighlight lang=idl>x=complex(1,1)
y=complex(!pi,1.2)
y=complex(!pi,1.2)
print,x+y
print,x+y
Line 2,585: Line 2,585:
( -1.00000, -1.00000)
( -1.00000, -1.00000)
print,1/x
print,1/x
( 0.500000, -0.500000)</lang>
( 0.500000, -0.500000)</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
Complex numbers are a native numeric data type in J. Although the examples shown here are performed on scalars, all numeric operations naturally apply to arrays of complex numbers.
Complex numbers are a native numeric data type in J. Although the examples shown here are performed on scalars, all numeric operations naturally apply to arrays of complex numbers.
<lang j> x=: 1j1
<syntaxhighlight lang=j> x=: 1j1
y=: 3.14159j1.2
y=: 3.14159j1.2
x+y NB. addition
x+y NB. addition
Line 2,601: Line 2,601:
+x NB. (complex) conjugation
+x NB. (complex) conjugation
1j_1
1j_1
</syntaxhighlight>
</lang>


=={{header|Java}}==
=={{header|Java}}==
<lang java>public class Complex {
<syntaxhighlight lang=java>public class Complex {
public final double real;
public final double real;
public final double imag;
public final double imag;
Line 2,655: Line 2,655:
System.out.println(a.conj());
System.out.println(a.conj());
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
<lang javascript>function Complex(r, i) {
<syntaxhighlight lang=javascript>function Complex(r, i) {
this.r = r;
this.r = r;
this.i = i;
this.i = i;
Line 2,712: Line 2,712:
Complex.prototype.getMod = function() {
Complex.prototype.getMod = function() {
return Math.sqrt( Math.pow(this.r,2) , Math.pow(this.i,2) )
return Math.sqrt( Math.pow(this.r,2) , Math.pow(this.i,2) )
}</lang>
}</syntaxhighlight>


=={{header|jq}}==
=={{header|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.
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.<lang jq>def real(z): if (z|type) == "number" then z else z[0] end;
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.<syntaxhighlight lang=jq>def real(z): if (z|type) == "number" then z else z[0] end;


def imag(z): if (z|type) == "number" then 0 else z[1] end;
def imag(z): if (z|type) == "number" then 0 else z[1] end;
Line 2,780: Line 2,780:
;
;


test( [1,1]; [0,1] )</lang>
test( [1,1]; [0,1] )</syntaxhighlight>
{{Out}}
{{Out}}
<lang jq>$ jq -n -f complex.jq
<syntaxhighlight lang=jq>$ jq -n -f complex.jq
"x = [1,1]"
"x = [1,1]"
"y = [0,1]"
"y = [0,1]"
Line 2,791: Line 2,791:
"conj(x): [1,-1]"
"conj(x): [1,-1]"
"(x/y)*y: [1,1]"
"(x/y)*y: [1,1]"
"e^iπ: [-1,1.2246467991473532e-16]"</lang>
"e^iπ: [-1,1.2246467991473532e-16]"</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
Julia has built-in support for complex arithmetic with arbitrary real types.
Julia has built-in support for complex arithmetic with arbitrary real types.
<lang julia>julia> z1 = 1.5 + 3im
<syntaxhighlight lang=julia>julia> z1 = 1.5 + 3im
julia> z2 = 1.5 + 1.5im
julia> z2 = 1.5 + 1.5im
julia> z1 + z2
julia> z1 + z2
Line 2,816: Line 2,816:
1.5
1.5
julia> imag(z1)
julia> imag(z1)
3.0</lang>
3.0</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>class Complex(private val real: Double, private val imag: Double) {
<syntaxhighlight lang=scala>class Complex(private val real: Double, private val imag: Double) {
operator fun plus(other: Complex) = Complex(real + other.real, imag + other.imag)
operator fun plus(other: Complex) = Complex(real + other.real, imag + other.imag)


Line 2,857: Line 2,857:
println("1 / x = ${x.inv()}")
println("1 / x = ${x.inv()}")
println("x* = ${x.conj()}")
println("x* = ${x.conj()}")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,873: Line 2,873:


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


Line 2,897: Line 2,897:
{C.mul {z1} {z2}} -> (0 3)
{C.mul {z1} {z2}} -> (0 3)
{C.div {z1} {z2}} -> (0.6666666666666667 0)
{C.div {z1} {z2}} -> (0.6666666666666667 0)
</syntaxhighlight>
</lang>


=={{header|LFE}}==
=={{header|LFE}}==
Line 2,904: Line 2,904:


A convenient data structure for a complex number is the record:
A convenient data structure for a complex number is the record:
<lang lisp>
<syntaxhighlight lang=lisp>
(defrecord complex
(defrecord complex
real
real
img)
img)
</syntaxhighlight>
</lang>


Here are the required functions:
Here are the required functions:


<lang lisp>
<syntaxhighlight lang=lisp>
(defun add
(defun add
(((match-complex real r1 img i1)
(((match-complex real r1 img i1)
Line 2,930: Line 2,930:
(defun inv (cmplx)
(defun inv (cmplx)
(div (conj cmplx) (modulus cmplx)))
(div (conj cmplx) (modulus cmplx)))
</syntaxhighlight>
</lang>


Bonus:
Bonus:


<lang lisp>
<syntaxhighlight lang=lisp>
(defun conj
(defun conj
(((match-complex real r img i))
(((match-complex real r img i))
(new r (* -1 i))))
(new r (* -1 i))))
</syntaxhighlight>
</lang>


The functions above are built using the following supporting functions:
The functions above are built using the following supporting functions:


<lang lisp>
<syntaxhighlight lang=lisp>
(defun new (r i)
(defun new (r i)
(make-complex real r img i))
(make-complex real r img i))
Line 2,955: Line 2,955:
(/ (complex-img c3) denom)))))
(/ (complex-img c3) denom)))))


</syntaxhighlight>
</lang>


Finally, we have some functions for use in the conversion and display of our complex number data structure:
Finally, we have some functions for use in the conversion and display of our complex number data structure:


<lang lisp>
<syntaxhighlight lang=lisp>
(defun ->str
(defun ->str
(((match-complex real r img i)) (when (>= i 0))
(((match-complex real r img i)) (when (>= i 0))
Line 2,971: Line 2,971:
(defun print (cmplx)
(defun print (cmplx)
(io:format (++ (->str cmplx) "~n")))
(io:format (++ (->str cmplx) "~n")))
</syntaxhighlight>
</lang>


Usage is as follows:
Usage is as follows:
Line 2,998: Line 2,998:


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>mainwin 50 10
<syntaxhighlight lang=lb>mainwin 50 10


print " Adding"
print " Adding"
Line 3,048: Line 3,048:
D =ar^2 +ai^2
D =ar^2 +ai^2
cinv$ =complex$( ar /D , 0 -ai /D )
cinv$ =complex$( ar /D , 0 -ai /D )
end function</lang>
end function</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>
<syntaxhighlight lang=lua>


--defines addition, subtraction, negation, multiplication, division, conjugation, norms, and a conversion to strgs.
--defines addition, subtraction, negation, multiplication, division, conjugation, norms, and a conversion to strgs.
Line 3,084: Line 3,084:
print("|" .. i .. "| = " .. math.sqrt(i.norm))
print("|" .. i .. "| = " .. math.sqrt(i.norm))
print(i .. "* = " .. i.conj)
print(i .. "* = " .. i.conj)
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
Line 3,090: Line 3,090:
Maple has <code>I</code> (the square root of -1) built-in. Thus:
Maple has <code>I</code> (the square root of -1) built-in. Thus:


<lang maple>x := 1+I;
<syntaxhighlight lang=maple>x := 1+I;
y := Pi+I*1.2;</lang>
y := Pi+I*1.2;</syntaxhighlight>


By itself, it will perform mathematical operations symbolically, i.e. it will not try to perform computational evaluation unless specifically asked to do so. Thus:
By itself, it will perform mathematical operations symbolically, i.e. it will not try to perform computational evaluation unless specifically asked to do so. Thus:


<lang maple>x*y;
<syntaxhighlight lang=maple>x*y;
==> (1 + I) (Pi + 1.2 I)
==> (1 + I) (Pi + 1.2 I)
simplify(x*y);
simplify(x*y);
==> 1.941592654 + 4.341592654 I</lang>
==> 1.941592654 + 4.341592654 I</syntaxhighlight>


Other than that, the task merely asks for
Other than that, the task merely asks for


<lang maple>x+y;
<syntaxhighlight lang=maple>x+y;
x*y;
x*y;
-x;
-x;
1/x;</lang>
1/x;</syntaxhighlight>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Mathematica has fully implemented support for complex numbers throughout the software. Addition, subtraction, division, multiplications and powering need no further syntax than for real numbers:
Mathematica has fully implemented support for complex numbers throughout the software. Addition, subtraction, division, multiplications and powering need no further syntax than for real numbers:
<lang Mathematica>x=1+2I
<syntaxhighlight lang=Mathematica>x=1+2I
y=3+4I
y=3+4I


Line 3,119: Line 3,119:
y^4 => -527 - 336 I
y^4 => -527 - 336 I
x^y => (1 + 2 I)^(3 + 4 I)
x^y => (1 + 2 I)^(3 + 4 I)
N[x^y] => 0.12901 + 0.0339241 I</lang>
N[x^y] => 0.12901 + 0.0339241 I</syntaxhighlight>
Powering to a complex power can in general not be written shorter, so Mathematica leaves it unevaluated if the numbers are exact. An approximation can be acquired using the function N.
Powering to a complex power can in general not be written shorter, so Mathematica leaves it unevaluated if the numbers are exact. An approximation can be acquired using the function N.
However Mathematica goes much further, basically all functions can handle complex numbers to arbitrary precision, including (but not limited to!):
However Mathematica goes much further, basically all functions can handle complex numbers to arbitrary precision, including (but not limited to!):
<lang Mathematica>Exp Log
<syntaxhighlight lang=Mathematica>Exp Log
Sin Cos Tan Csc Sec Cot
Sin Cos Tan Csc Sec Cot
ArcSin ArcCos ArcTan ArcCsc ArcSec ArcCot
ArcSin ArcCos ArcTan ArcCsc ArcSec ArcCot
Line 3,130: Line 3,130:
Haversine InverseHaversine
Haversine InverseHaversine
Factorial Gamma PolyGamma LogGamma
Factorial Gamma PolyGamma LogGamma
Erf BarnesG Hyperfactorial Zeta ProductLog RamanujanTauL</lang>
Erf BarnesG Hyperfactorial Zeta ProductLog RamanujanTauL</syntaxhighlight>
and many many more. The documentation states:
and many many more. The documentation states:


Line 3,138: Line 3,138:
Complex numbers are a primitive data type in MATLAB. All the typical complex operations can be performed. There are two keywords that specify a number as complex: "i" and "j".
Complex numbers are a primitive data type in MATLAB. All the typical complex operations can be performed. There are two keywords that specify a number as complex: "i" and "j".


<lang MATLAB>>> a = 1+i
<syntaxhighlight lang=MATLAB>>> a = 1+i


a =
a =
Line 3,196: Line 3,196:
ans =
ans =


1.414213562373095</lang>
1.414213562373095</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>z1: 5 + 2 * %i;
<syntaxhighlight lang=maxima>z1: 5 + 2 * %i;
2*%i+5
2*%i+5


Line 3,242: Line 3,242:


imagpart(z1);
imagpart(z1);
2</lang>
2</syntaxhighlight>


=={{header|МК-61/52}}==
=={{header|МК-61/52}}==
Line 3,260: Line 3,260:
+ П2 ИП1 С/П ИПB ИПD + П2 ИПA ИПC
+ П2 ИП1 С/П ИПB ИПD + П2 ИПA ИПC
+ ИП1 С/П ИПB ИПD - П2 ИПA ИПC -
+ ИП1 С/П ИПB ИПD - П2 ИПA ИПC -
П1 С/П</lang>
П1 С/П</syntaxhighlight>


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE complex;
<syntaxhighlight lang=modula2>MODULE complex;


IMPORT InOut;
IMPORT InOut;
Line 3,328: Line 3,328:
NegComplex (z[0], z[2]); ShowComplex (" - z1", z[2]);
NegComplex (z[0], z[2]); ShowComplex (" - z1", z[2]);
InOut.WriteLn
InOut.WriteLn
END complex.</lang>
END complex.</syntaxhighlight>
{{out}}
{{out}}
<pre>Enter two complex numbers : 5 3 0.5 6
<pre>Enter two complex numbers : 5 3 0.5 6
Line 3,343: Line 3,343:
{{trans|Java}}
{{trans|Java}}
This is a translation of the Java version, but it uses operator redefinition where possible.
This is a translation of the Java version, but it uses operator redefinition where possible.
<lang nanoquery>import math
<syntaxhighlight lang=nanoquery>import math


class Complex
class Complex
Line 3,398: Line 3,398:
println a.inv()
println a.inv()
println a * b
println a * b
println a.conj()</lang>
println a.conj()</syntaxhighlight>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>using System;
<syntaxhighlight lang=Nemerle>using System;
using System.Console;
using System.Console;
using System.Numerics;
using System.Numerics;
Line 3,426: Line 3,426:
WriteLine(Conjugate(complex2).PrettyPrint());
WriteLine(Conjugate(complex2).PrettyPrint());
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>4.14159 + 2.2i
<pre>4.14159 + 2.2i
Line 3,435: Line 3,435:


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>
<syntaxhighlight lang=nim>
import complex
import complex
var a: Complex = (1.0,1.0)
var a: Complex = (1.0,1.0)
Line 3,447: Line 3,447:
echo("-a : " & $(-a))
echo("-a : " & $(-a))


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,460: Line 3,460:
=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
Oxford Oberon Compiler
Oxford Oberon Compiler
<lang oberon2>
<syntaxhighlight lang=oberon2>
MODULE Complex;
MODULE Complex;
IMPORT Files,Out;
IMPORT Files,Out;
Line 3,546: Line 3,546:
END Complex.
END Complex.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,561: Line 3,561:
=={{header|OCaml}}==
=={{header|OCaml}}==
The [http://caml.inria.fr/pub/docs/manual-ocaml/libref/Complex.html Complex] module from the standard library provides the functionality of complex numbers:
The [http://caml.inria.fr/pub/docs/manual-ocaml/libref/Complex.html Complex] module from the standard library provides the functionality of complex numbers:
<lang ocaml>open Complex
<syntaxhighlight lang=ocaml>open Complex


let print_complex z =
let print_complex z =
Line 3,573: Line 3,573:
print_complex (inv a);
print_complex (inv a);
print_complex (neg a);
print_complex (neg a);
print_complex (conj a)</lang>
print_complex (conj a)</syntaxhighlight>


Using [http://forge.ocamlcore.org/projects/pa-do/ Delimited Overloading], the syntax can be made closer to the usual one:
Using [http://forge.ocamlcore.org/projects/pa-do/ Delimited Overloading], the syntax can be made closer to the usual one:
<lang ocaml>let () =
<syntaxhighlight lang=ocaml>let () =
Complex.(
Complex.(
let print txt z = Printf.printf "%s = %s\n" txt (to_string z) in
let print txt z = Printf.printf "%s = %s\n" txt (to_string z) in
Line 3,589: Line 3,589:
print "a^b" (a**b);
print "a^b" (a**b);
Printf.printf "norm a = %g\n" (float(abs a));
Printf.printf "norm a = %g\n" (float(abs a));
)</lang>
)</syntaxhighlight>


=={{header|Octave}}==
=={{header|Octave}}==
GNU Octave handles naturally complex numbers:
GNU Octave handles naturally complex numbers:
<lang octave>z1 = 1.5 + 3i;
<syntaxhighlight lang=octave>z1 = 1.5 + 3i;
z2 = 1.5 + 1.5i;
z2 = 1.5 + 1.5i;
disp(z1 + z2); % 3.0 + 4.5i
disp(z1 + z2); % 3.0 + 4.5i
Line 3,606: Line 3,606:
disp( imag(z1) ); % 3
disp( imag(z1) ); % 3
disp( real(z2) ); % 1.5
disp( real(z2) ); % 1.5
%...</lang>
%...</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>Object Class new: Complex(re, im)
<syntaxhighlight lang=Oforth>Object Class new: Complex(re, im)
Complex method: re @re ;
Complex method: re @re ;
Line 3,648: Line 3,648:


Integer method: >complex self 0 Complex new ;
Integer method: >complex self 0 Complex new ;
Float method: >complex self 0 Complex new ;</lang>
Float method: >complex self 0 Complex new ;</syntaxhighlight>


Usage :
Usage :


<lang Oforth>3.2 >complex I * 2 >complex + .cr
<syntaxhighlight lang=Oforth>3.2 >complex I * 2 >complex + .cr
2 3 Complex new 1.2 >complex + .cr
2 3 Complex new 1.2 >complex + .cr
2 3 Complex new 1.2 >complex * .cr
2 3 Complex new 1.2 >complex * .cr
2 >complex 2 3 Complex new / .cr</lang>
2 >complex 2 3 Complex new / .cr</syntaxhighlight>


{{out}}
{{out}}
Line 3,668: Line 3,668:
Ol supports complex numbers by default. Numbers must be entered manually in form A+Bi without spaces between elements, where A and B - numbers (can be rational), i - imaginary unit; or in functional form using function `complex`.
Ol supports complex numbers by default. Numbers must be entered manually in form A+Bi without spaces between elements, where A and B - numbers (can be rational), i - imaginary unit; or in functional form using function `complex`.


<lang scheme>
<syntaxhighlight lang=scheme>
(define A 0+1i) ; manually entered numbers
(define A 0+1i) ; manually entered numbers
(define B 1+0i)
(define B 1+0i)
Line 3,692: Line 3,692:
(print "imaginary part of " C " is " (cdr C))
(print "imaginary part of " C " is " (cdr C))
; <== imaginary part of 2/7-3i is -3
; <== imaginary part of 2/7-3i is -3
</syntaxhighlight>
</lang>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<lang ooRexx>c1 = .complex~new(1, 2)
<syntaxhighlight lang=ooRexx>c1 = .complex~new(1, 2)
c2 = .complex~new(3, 4)
c2 = .complex~new(3, 4)
r = 7
r = 7
Line 3,831: Line 3,831:
::method hashCode
::method hashCode
expose r i
expose r i
return r~hashcode~bitxor(i~hashcode)</lang>
return r~hashcode~bitxor(i~hashcode)</syntaxhighlight>
{{out}}
{{out}}
<pre>c1 = 1 + 2i
<pre>c1 = 1 + 2i
Line 3,852: Line 3,852:
=={{header|OxygenBasic}}==
=={{header|OxygenBasic}}==
Implementation of a complex numbers class with arithmetical operations, and powers using DeMoivre's theorem (polar conversion).
Implementation of a complex numbers class with arithmetical operations, and powers using DeMoivre's theorem (polar conversion).
<lang oxygenbasic>
<syntaxhighlight lang=oxygenbasic>
'COMPLEX OPERATIONS
'COMPLEX OPERATIONS
'=================
'=================
Line 3,985: Line 3,985:
z1 = z1*z4
z1 = z1*z4
print "Z1 = "+z1.show 'RESULT 2.0, 1.0
print "Z1 = "+z1.show 'RESULT 2.0, 1.0
</syntaxhighlight>
</lang>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
To use, type, e.g., inv(3 + 7*I).
To use, type, e.g., inv(3 + 7*I).
<lang parigp>add(a,b)=a+b;
<syntaxhighlight lang=parigp>add(a,b)=a+b;
mult(a,b)=a*b;
mult(a,b)=a*b;
neg(a)=-a;
neg(a)=-a;
inv(a)=1/a;</lang>
inv(a)=1/a;</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
{{works with|Extended Pascal}}
{{works with|Extended Pascal}}
The simple data type <tt>complex</tt> is part of Extended Pascal, ISO standard 10206.
The simple data type <tt>complex</tt> is part of Extended Pascal, ISO standard 10206.
<lang pascal>program complexDemo(output);
<syntaxhighlight lang=pascal>program complexDemo(output);


const
const
Line 4,063: Line 4,063:
writeLn(' inverse(', asString(z), ') = ', asString(inverse(z)));
writeLn(' inverse(', asString(z), ') = ', asString(inverse(z)));
writeLn(' conjugation(', asString(y), ') = ', asString(conjugation(y)));
writeLn(' conjugation(', asString(y), ') = ', asString(conjugation(y)));
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>(-3.00, 2.00) + ( 1.00, 4.00) = (-2.00, 6.00)
<pre>(-3.00, 2.00) + ( 1.00, 4.00) = (-2.00, 6.00)
Line 4,077: Line 4,077:
=={{header|Perl}}==
=={{header|Perl}}==
The <code>Math::Complex</code> module implements complex arithmetic.
The <code>Math::Complex</code> module implements complex arithmetic.
<lang perl>use Math::Complex;
<syntaxhighlight lang=perl>use Math::Complex;
my $a = 1 + 1*i;
my $a = 1 + 1*i;
my $b = 3.14159 + 1.25*i;
my $b = 3.14159 + 1.25*i;
Line 4,086: Line 4,086:
-$a, # negation
-$a, # negation
1 / $a, # multiplicative inverse
1 / $a, # multiplicative inverse
~$a; # complex conjugate</lang>
~$a; # complex conjugate</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\ArithComplex.exw</span>
<span style="color: #000080;font-style:italic;">-- demo\rosetta\ArithComplex.exw</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 4,109: Line 4,109:
<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;">"-a = %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">complex_sprint</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">complex_neg</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">))})</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;">"-a = %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">complex_sprint</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">complex_neg</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">))})</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;">"conj a = %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">complex_sprint</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">complex_conjugate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">))})</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;">"conj a = %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">complex_sprint</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">complex_conjugate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">))})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 4,127: Line 4,127:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(load "@lib/math.l")
<syntaxhighlight lang=PicoLisp>(load "@lib/math.l")


(de addComplex (A B)
(de addComplex (A B)
Line 4,168: Line 4,168:
(prinl "A*B = " (fmtComplex (mulComplex A B)))
(prinl "A*B = " (fmtComplex (mulComplex A B)))
(prinl "1/A = " (fmtComplex (invComplex A)))
(prinl "1/A = " (fmtComplex (invComplex A)))
(prinl "-A = " (fmtComplex (negComplex A))) )</lang>
(prinl "-A = " (fmtComplex (negComplex A))) )</syntaxhighlight>
{{out}}
{{out}}
<pre>A = 1.00000+1.00000i
<pre>A = 1.00000+1.00000i
Line 4,178: Line 4,178:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>/* PL/I complex numbers may be integer or floating-point. */
<syntaxhighlight lang=pli>/* PL/I complex numbers may be integer or floating-point. */
/* In this example, the variables are floating-pint. */
/* In this example, the variables are floating-pint. */
/* For integer variables, change 'float' to 'fixed binary' */
/* For integer variables, change 'float' to 'fixed binary' */
Line 4,198: Line 4,198:


/* As well, trigonometric functions may be used with complex */
/* As well, trigonometric functions may be used with complex */
/* numbers, such as SIN, COS, TAN, ATAN, and so on. */</lang>
/* numbers, such as SIN, COS, TAN, ATAN, and so on. */</syntaxhighlight>


=={{header|Pop11}}==
=={{header|Pop11}}==
Line 4,211: Line 4,211:
'1 -: 3' is '1 - 3i' in mathematical notation.
'1 -: 3' is '1 - 3i' in mathematical notation.


<lang pop11>lvars a = 1.0 +: 1.0, b = 2.0 +: 5.0 ;
<syntaxhighlight lang=pop11>lvars a = 1.0 +: 1.0, b = 2.0 +: 5.0 ;
a+b =>
a+b =>
a*b =>
a*b =>
Line 4,229: Line 4,229:
a-a =>
a-a =>
a/b =>
a/b =>
a/a =></lang>
a/a =></syntaxhighlight>


=={{header|PostScript}}==
=={{header|PostScript}}==
Line 4,282: Line 4,282:
}def
}def


</syntaxhighlight>
</lang>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
===Implementation===
===Implementation===
<lang PowerShell>
<syntaxhighlight lang=PowerShell>
class Complex {
class Complex {
[Double]$x
[Double]$x
Line 4,326: Line 4,326:
"1/`$m: $([complex]::show($m.inverse()))"
"1/`$m: $([complex]::show($m.inverse()))"
"conjugate `$m: $([complex]::show($m.conjugate()))"
"conjugate `$m: $([complex]::show($m.conjugate()))"
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 4,338: Line 4,338:
</pre>
</pre>
===Library===
===Library===
<lang PowerShell>
<syntaxhighlight lang=PowerShell>
function show([System.Numerics.Complex]$c) {
function show([System.Numerics.Complex]$c) {
if(0 -le $c.Imaginary) {
if(0 -le $c.Imaginary) {
Line 4,355: Line 4,355:
"1/`$m: $(show ([System.Numerics.Complex]::Reciprocal($m)))"
"1/`$m: $(show ([System.Numerics.Complex]::Reciprocal($m)))"
"conjugate `$m: $(show ([System.Numerics.Complex]::Conjugate($m)))"
"conjugate `$m: $(show ([System.Numerics.Complex]::Conjugate($m)))"
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 4,368: Line 4,368:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Structure Complex
<syntaxhighlight lang=PureBasic>Structure Complex
real.d
real.d
imag.d
imag.d
Line 4,432: Line 4,432:
*c=Neg_Complex(a): ShowAndFree("-a", *c)
*c=Neg_Complex(a): ShowAndFree("-a", *c)
Print(#CRLF$+"Press ENTER to exit"):Input()
Print(#CRLF$+"Press ENTER to exit"):Input()
EndIf</lang>
EndIf</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==


<lang python>>>> z1 = 1.5 + 3j
<syntaxhighlight lang=python>>>> z1 = 1.5 + 3j
>>> z2 = 1.5 + 1.5j
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
>>> z1 + z2
Line 4,458: Line 4,458:
>>> z1.imag
>>> z1.imag
3.0
3.0
>>> </lang>
>>> </syntaxhighlight>


=={{header|R}}==
=={{header|R}}==
{{trans|Octave}}
{{trans|Octave}}


<lang rsplus>z1 <- 1.5 + 3i
<syntaxhighlight lang=rsplus>z1 <- 1.5 + 3i
z2 <- 1.5 + 1.5i
z2 <- 1.5 + 1.5i
print(z1 + z2) # 3+4.5i
print(z1 + z2) # 3+4.5i
Line 4,475: Line 4,475:
print(exp(z1)) # -4.436839+0.632456i
print(exp(z1)) # -4.436839+0.632456i
print(Re(z1)) # 1.5
print(Re(z1)) # 1.5
print(Im(z1)) # 3</lang>
print(Im(z1)) # 3</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>
<syntaxhighlight lang=racket>
#lang racket
#lang racket


Line 4,492: Line 4,492:
(/ 1 a) ; reciprocal
(/ 1 a) ; reciprocal
(conjugate a) ; conjugation
(conjugate a) ; conjugation
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 4,498: Line 4,498:
{{works with|Rakudo|2015.12}}
{{works with|Rakudo|2015.12}}


<lang perl6>my $a = 1 + i;
<syntaxhighlight lang=perl6>my $a = 1 + i;
my $b = pi + 1.25i;
my $b = pi + 1.25i;


.say for $a + $b, $a * $b, -$a, 1 / $a, $a.conj;
.say for $a + $b, $a * $b, -$a, 1 / $a, $a.conj;
.say for $a.abs, $a.sqrt, $a.re, $a.im;</lang>
.say for $a.abs, $a.sqrt, $a.re, $a.im;</syntaxhighlight>
{{out}} (precision varies with different implementations):
{{out}} (precision varies with different implementations):
<pre>
<pre>
Line 4,518: Line 4,518:
=={{header|REXX}}==
=={{header|REXX}}==
The REXX language has no complex type numbers, but most complex arithmetic functions can easily be written.
The REXX language has no complex type numbers, but most complex arithmetic functions can easily be written.
<lang rexx>/*REXX program demonstrates how to support some math functions for complex numbers. */
<syntaxhighlight lang=rexx>/*REXX program demonstrates how to support some math functions for complex numbers. */
x = '(5,3i)' /*define X ─── can use I i J or j */
x = '(5,3i)' /*define X ─── can use I i J or j */
y = "( .5, 6j)" /*define Y " " " " " " " */
y = "( .5, 6j)" /*define Y " " " " " " " */
Line 4,540: Line 4,540:
C_: return word(translate(arg(1), , '{[(JjIi)]}') 0, 1) /*get # or 0*/
C_: return word(translate(arg(1), , '{[(JjIi)]}') 0, 1) /*get # or 0*/
C#: a=C_(a); b=C_(b); c=C_(c); d=C_(d); ac=a*c; ad=a*d; bc=b*c; bd=b*d;s=c*c+d*d; return
C#: a=C_(a); b=C_(b); c=C_(c); d=C_(d); ac=a*c; ad=a*d; bc=b*c; bd=b*d;s=c*c+d*d; return
C$: parse arg r,c; _='['r; if c\=0 then _=_","c'j'; return _"]" /*uses j */</lang>
C$: parse arg r,c; _='['r; if c\=0 then _=_","c'j'; return _"]" /*uses j */</syntaxhighlight>
'''output'''
'''output'''
<pre>
<pre>
Line 4,554: Line 4,554:
=={{header|RLaB}}==
=={{header|RLaB}}==


<lang RLaB>
<syntaxhighlight lang=RLaB>
>> x = sqrt(-1)
>> x = sqrt(-1)
0 + 1i
0 + 1i
Line 4,563: Line 4,563:
>> isreal(z)
>> isreal(z)
1
1
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>
<syntaxhighlight lang=ruby>
# Four ways to write complex numbers:
# Four ways to write complex numbers:
a = Complex(1, 1) # 1. call Kernel#Complex
a = Complex(1, 1) # 1. call Kernel#Complex
Line 4,580: Line 4,580:
puts 1.quo a # multiplicative inverse
puts 1.quo a # multiplicative inverse
puts a.conjugate # complex conjugate
puts a.conjugate # complex conjugate
puts a.conj # alias for complex conjugate</lang>
puts a.conj # alias for complex conjugate</syntaxhighlight>


''Notes:''
''Notes:''
* All of these operations are safe with other numeric types. For example, <code>42.conjugate</code> returns 42.
* All of these operations are safe with other numeric types. For example, <code>42.conjugate</code> returns 42.


<lang ruby># Other ways to find the multiplicative inverse:
<syntaxhighlight lang=ruby># Other ways to find the multiplicative inverse:
puts 1.quo a # always works
puts 1.quo a # always works
puts 1.0 / a # works, but forces floating-point math
puts 1.0 / a # works, but forces floating-point math
puts 1 / a # might truncate to integer</lang>
puts 1 / a # might truncate to integer</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>extern crate num;
<syntaxhighlight lang=rust>extern crate num;
use num::complex::Complex;
use num::complex::Complex;


Line 4,606: Line 4,606:
println!(" -a = {}", -a);
println!(" -a = {}", -a);
println!("conj(a) = {}", a.conj());
println!("conj(a) = {}", a.conj());
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
Line 4,612: Line 4,612:
Scala doesn't come with a Complex library, but one can be made:
Scala doesn't come with a Complex library, but one can be made:


<lang scala>package org.rosettacode
<syntaxhighlight lang=scala>package org.rosettacode


package object ArithmeticComplex {
package object ArithmeticComplex {
Line 4,646: Line 4,646:
def fromPolar(rho:Double, theta:Double) = Complex(rho*math.cos(theta), rho*math.sin(theta))
def fromPolar(rho:Double, theta:Double) = Complex(rho*math.cos(theta), rho*math.sin(theta))
}
}
}</lang>
}</syntaxhighlight>


Usage example:
Usage example:


<lang scala>scala> import org.rosettacode.ArithmeticComplex._
<syntaxhighlight lang=scala>scala> import org.rosettacode.ArithmeticComplex._
import org.rosettacode.ArithmeticComplex._
import org.rosettacode.ArithmeticComplex._


Line 4,676: Line 4,676:
scala> -res6
scala> -res6
res7: org.rosettacode.ArithmeticComplex.Complex = -0.2 + 0.4i
res7: org.rosettacode.ArithmeticComplex.Complex = -0.2 + 0.4i
</syntaxhighlight>
</lang>


=={{header|Scheme}}==
=={{header|Scheme}}==
Line 4,682: Line 4,682:
* rectangular coordinates: <code>''real''+''imag''i</code> (or <code>''real''-''imag''i</code>), where ''real'' is the real part and ''imag'' is the imaginary part. For a pure-imaginary number, the real part may be omitted but the sign of the imaginary part is mandatory (even if it is "+"): <code>+''imag''i</code> (or <code>-''imag''i</code>). If the imaginary part is 1 or -1, the imaginary part can be omitted, leaving only the <code>+i</code> or <code>-i</code> at the end.
* rectangular coordinates: <code>''real''+''imag''i</code> (or <code>''real''-''imag''i</code>), where ''real'' is the real part and ''imag'' is the imaginary part. For a pure-imaginary number, the real part may be omitted but the sign of the imaginary part is mandatory (even if it is "+"): <code>+''imag''i</code> (or <code>-''imag''i</code>). If the imaginary part is 1 or -1, the imaginary part can be omitted, leaving only the <code>+i</code> or <code>-i</code> at the end.
* polar coordinates: <code>''r''@''theta''</code>, where ''r'' is the absolute value (magnitude) and ''theta'' is the angle
* polar coordinates: <code>''r''@''theta''</code>, where ''r'' is the absolute value (magnitude) and ''theta'' is the angle
<lang scheme>(define a 1+i)
<syntaxhighlight lang=scheme>(define a 1+i)
(define b 3.14159+1.25i)
(define b 3.14159+1.25i)


Line 4,688: Line 4,688:
(define c (* a b))
(define c (* a b))
(define c (/ 1 a))
(define c (/ 1 a))
(define c (- a))</lang>
(define c (- a))</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==


<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang=seed7>$ include "seed7_05.s7i";
include "float.s7i";
include "float.s7i";
include "complex.s7i";
include "complex.s7i";
Line 4,711: Line 4,711:
# negation
# negation
writeln("-a=" <& -a digits 5);
writeln("-a=" <& -a digits 5);
end func;</lang>
end func;</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>var a = 1:1 # Complex(1, 1)
<syntaxhighlight lang=ruby>var a = 1:1 # Complex(1, 1)
var b = 3.14159:1.25 # Complex(3.14159, 1.25)
var b = 3.14159:1.25 # Complex(3.14159, 1.25)
Line 4,726: Line 4,726:
b.re, # real
b.re, # real
b.im, # imaginary
b.im, # imaginary
].each { |c| say c }</lang>
].each { |c| say c }</syntaxhighlight>
{{out}}
{{out}}
<pre>4.14159+2.25i
<pre>4.14159+2.25i
Line 4,740: Line 4,740:
=={{header|Slate}}==
=={{header|Slate}}==


<lang slate>[| a b |
<syntaxhighlight lang=slate>[| a b |
a: 1 + 1 i.
a: 1 + 1 i.
b: Pi + 1.2 i.
b: Pi + 1.2 i.
Line 4,750: Line 4,750:
print: a abs.
print: a abs.
print: a negated.
print: a negated.
].</lang>
].</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
{{works with|GNU Smalltalk}}
<lang smalltalk>PackageLoader fileInPackage: 'Complex'.
<syntaxhighlight lang=smalltalk>PackageLoader fileInPackage: 'Complex'.
|a b|
|a b|
a := 1 + 1 i.
a := 1 + 1 i.
Line 4,766: Line 4,766:
a real displayNl.
a real displayNl.
a imaginary displayNl.
a imaginary displayNl.
a negated displayNl.</lang>
a negated displayNl.</syntaxhighlight>
{{works with|Smalltalk/X}}
{{works with|Smalltalk/X}}
Complex is already in the basic class library. Multiples of imaginary are created by sending an "i" message to a number, which can be added to another number. Thus 5i => (0+5i), 1+(1/3)I => (1+1/3i) and (1.0+2i) => (1.0+2i). Notice that the real and imaginary components can be arbitrary integers, fractions or floating point numbers. And the results will be exact (i.e. have fractions or integer) if possible.
Complex is already in the basic class library. Multiples of imaginary are created by sending an "i" message to a number, which can be added to another number. Thus 5i => (0+5i), 1+(1/3)I => (1+1/3i) and (1.0+2i) => (1.0+2i). Notice that the real and imaginary components can be arbitrary integers, fractions or floating point numbers. And the results will be exact (i.e. have fractions or integer) if possible.
<lang smalltalk>
<syntaxhighlight lang=smalltalk>
|a b|
|a b|
a := 1 + 1i.
a := 1 + 1i.
Line 4,792: Line 4,792:
Transcript show:'a2*b2 => '; showCR:(a2 * b2).
Transcript show:'a2*b2 => '; showCR:(a2 * b2).
Transcript show:'a2/b2 => '; showCR:(a2 / b2).
Transcript show:'a2/b2 => '; showCR:(a2 / b2).
Transcript show:'a2 reciprocal => '; showCR:a2 reciprocal.</lang>
Transcript show:'a2 reciprocal => '; showCR:a2 reciprocal.</syntaxhighlight>
{{out}}
{{out}}
<pre>a => (1+1i)
<pre>a => (1+1i)
Line 4,817: Line 4,817:
<b>Original author unknown {:o(</b>
<b>Original author unknown {:o(</b>


<lang qbasic>' complex numbers are native for "smart BASIC"
<syntaxhighlight lang=qbasic>' complex numbers are native for "smart BASIC"
A=1+2i
A=1+2i
B=3-5i
B=3-5i
Line 4,833: Line 4,833:


' gives output
' gives output
-1+2i -1-2i</lang>
-1+2i -1-2i</syntaxhighlight>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
Line 4,841: Line 4,841:
{{works with|CSnobol}}
{{works with|CSnobol}}


<lang SNOBOL4>* # Define complex datatype
<syntaxhighlight lang=SNOBOL4>* # Define complex datatype
data('complex(r,i)')
data('complex(r,i)')


Line 4,880: Line 4,880:
output = printx( negx(a) ) ', ' printx( negx(b) )
output = printx( negx(a) ) ', ' printx( negx(b) )
output = printx( invx(a) ) ', ' printx( invx(b) )
output = printx( invx(a) ) ', ' printx( invx(b) )
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 4,889: Line 4,889:


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang Standard ML>
<syntaxhighlight lang=Standard ML>
(* Signature for complex numbers *)
(* Signature for complex numbers *)
signature COMPLEX = sig
signature COMPLEX = sig
Line 4,933: Line 4,933:
Complex.print_number(Complex.times i1 i2); (* -5 + 10i *)
Complex.print_number(Complex.times i1 i2); (* -5 + 10i *)
Complex.print_number(Complex.invert i1); (* 1/5 - 2i/5 *)
Complex.print_number(Complex.invert i1); (* 1/5 - 2i/5 *)
</syntaxhighlight>
</lang>


=={{header|Stata}}==
=={{header|Stata}}==


<lang stata>mata
<syntaxhighlight lang=stata>mata
C(2,3)
C(2,3)
2 + 3i
2 + 3i
Line 4,978: Line 4,978:
1.28247468 + .982793723i
1.28247468 + .982793723i


end</lang>
end</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
Line 4,985: Line 4,985:
Use a struct to create a complex number type in Swift. Math Operations can be added using operator overloading
Use a struct to create a complex number type in Swift. Math Operations can be added using operator overloading


<lang swift>
<syntaxhighlight lang=swift>
public struct Complex {
public struct Complex {
Line 5,032: Line 5,032:
}
}


</syntaxhighlight>
</lang>


Make the Complex Number struct printable and easier to debug by adding making it conform to CustomStringConvertible
Make the Complex Number struct printable and easier to debug by adding making it conform to CustomStringConvertible


<lang swift>
<syntaxhighlight lang=swift>


extension Complex : CustomStringConvertible {
extension Complex : CustomStringConvertible {
Line 5,063: Line 5,063:
}
}


</syntaxhighlight>
</lang>


Explicitly support subtraction and division
Explicitly support subtraction and division


<lang swift>
<syntaxhighlight lang=swift>
public func - (left:Complex, right:Complex) -> Complex {
public func - (left:Complex, right:Complex) -> Complex {
return left + -right
return left + -right
Line 5,078: Line 5,078:
return Complex(real: num.real/den.real, imaginary: num.imaginary/den.real)
return Complex(real: num.real/den.real, imaginary: num.imaginary/den.real)
}
}
</syntaxhighlight>
</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==
{{tcllib|math::complexnumbers}}
{{tcllib|math::complexnumbers}}
<lang tcl>package require math::complexnumbers
<syntaxhighlight lang=tcl>package require math::complexnumbers
namespace import math::complexnumbers::*
namespace import math::complexnumbers::*


Line 5,090: Line 5,090:
puts [tostring [* $a $b]] ;# ==> 1.94159+4.34159i
puts [tostring [* $a $b]] ;# ==> 1.94159+4.34159i
puts [tostring [pow $a [complex -1 0]]] ;# ==> 0.5-0.4999999999999999i
puts [tostring [pow $a [complex -1 0]]] ;# ==> 0.5-0.4999999999999999i
puts [tostring [- $a]] ;# ==> -1.0-i</lang>
puts [tostring [- $a]] ;# ==> -1.0-i</syntaxhighlight>


=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==
Line 5,128: Line 5,128:
=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|ksh93}}
{{works with|ksh93}}
<lang bash>typeset -T Complex_t=(
<syntaxhighlight lang=bash>typeset -T Complex_t=(
float real=0
float real=0
float imag=0
float imag=0
Line 5,202: Line 5,202:
Complex_t d=(real=2 imag=1)
Complex_t d=(real=2 imag=1)
d.inverse
d.inverse
d.to_s # 0.4 + -0.2 i</lang>
d.to_s # 0.4 + -0.2 i</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
Line 5,212: Line 5,212:
c..add or ..csin). Real operands are promoted to complex.
c..add or ..csin). Real operands are promoted to complex.


<lang Ursala>u = 3.785e+00-1.969e+00i
<syntaxhighlight lang=Ursala>u = 3.785e+00-1.969e+00i
v = 9.545e-01-3.305e+00j
v = 9.545e-01-3.305e+00j


Line 5,223: Line 5,223:
complex..mul (u,v),
complex..mul (u,v),
complex..sub (0.,u),
complex..sub (0.,u),
complex..div (1.,v)></lang>
complex..div (1.,v)></syntaxhighlight>
{{out}}
{{out}}
<pre><
<pre><
Line 5,233: Line 5,233:


=={{header|VBA}}==
=={{header|VBA}}==
<lang VBA>
<syntaxhighlight lang=VBA>
Public Type Complex
Public Type Complex
re As Double
re As Double
Line 5,322: Line 5,322:
Debug.Print "Sqrt(a) = " & CPrint(c)
Debug.Print "Sqrt(a) = " & CPrint(c)
End Sub
End Sub
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 5,339: Line 5,339:


=={{header|Vlang}}==
=={{header|Vlang}}==
<lang vlang>import math.complex
<syntaxhighlight lang=vlang>import math.complex
fn main() {
fn main() {
a := complex.complex(1, 1)
a := complex.complex(1, 1)
Line 5,350: Line 5,350:
println("1 / a: ${complex.complex(1,0)/a}")
println("1 / a: ${complex.complex(1,0)/a}")
println("a̅: ${a.conjugate()}")
println("a̅: ${a.conjugate()}")
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>a: 1.000000+1.000000i
<pre>a: 1.000000+1.000000i
Line 5,363: Line 5,363:
=={{header|Wortel}}==
=={{header|Wortel}}==
{{trans|CoffeeScript}}
{{trans|CoffeeScript}}
<lang wortel>@class Complex {
<syntaxhighlight lang=wortel>@class Complex {
&[r i] @: {
&[r i] @: {
^r || r 0
^r || r 0
Line 5,392: Line 5,392:
"1 / ({b}) = {b.inv.}"
"1 / ({b}) = {b.inv.}"
"({!a.mul b}) / ({b}) = {`!.mul b.inv. !a.mul b}"
"({!a.mul b}) / ({b}) = {`!.mul b.inv. !a.mul b}"
]</lang>
]</syntaxhighlight>
{{out}}
{{out}}
<pre>(5 + 3i) + (4 - 3i) = 9
<pre>(5 + 3i) + (4 - 3i) = 9
Line 5,403: Line 5,403:
=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-complex}}
{{libheader|Wren-complex}}
<lang ecmascript>import "/complex" for Complex
<syntaxhighlight lang=ecmascript>import "/complex" for Complex


var x = Complex.new(1, 3)
var x = Complex.new(1, 3)
Line 5,415: Line 5,415:
System.print("-x = %(-x)")
System.print("-x = %(-x)")
System.print("1 / x = %(x.inverse)")
System.print("1 / x = %(x.inverse)")
System.print("x* = %(x.conj)")</lang>
System.print("x* = %(x.conj)")</syntaxhighlight>


{{out}}
{{out}}
Line 5,431: Line 5,431:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes;
<syntaxhighlight lang=XPL0>include c:\cxpl\codes;


func real CAdd(A, B, C); \Return complex sum of two complex numbers
func real CAdd(A, B, C); \Return complex sum of two complex numbers
Line 5,487: Line 5,487:
COut(0, CInv(U,W)); CrLf(0);
COut(0, CInv(U,W)); CrLf(0);
COut(0, Conj(U,W)); CrLf(0);
COut(0, Conj(U,W)); CrLf(0);
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 5,499: Line 5,499:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang Yabasic>rem ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
<syntaxhighlight lang=Yabasic>rem ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
rem CADDI/CADDR addition of complex numbers Z1 + Z2 with Z1 = a1 + b1 *i Z2 = a2 + b2*i
rem CADDI/CADDR addition of complex numbers Z1 + Z2 with Z1 = a1 + b1 *i Z2 = a2 + b2*i
rem CADDI returns imaginary part and CADDR the real part
rem CADDI returns imaginary part and CADDR the real part
Line 5,546: Line 5,546:
print "Example: Z1 + Z2 with Z1 = 3 +2i , Z2 = 1-3i: Z1 + Z2 = 4 -1i"
print "Example: Z1 + Z2 with Z1 = 3 +2i , Z2 = 1-3i: Z1 + Z2 = 4 -1i"
print caddr(3,2,1,-2), "/", caddi(3,2,1,-3) // 4/-1
print caddr(3,2,1,-2), "/", caddi(3,2,1,-3) // 4/-1
end if</lang>
end if</syntaxhighlight>


=={{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)
(GSL.Z(3,4) + GSL.Z(1,2)).println(); // (4.00+6.00i)
(GSL.Z(3,4) + GSL.Z(1,2)).println(); // (4.00+6.00i)
(GSL.Z(3,4) - GSL.Z(1,2)).println(); // (2.00+2.00i)
(GSL.Z(3,4) - GSL.Z(1,2)).println(); // (2.00+2.00i)
Line 5,556: Line 5,556:
(GSL.Z(1,0) / GSL.Z(1,1)).println(); // (0.50-0.50i) // inversion
(GSL.Z(1,0) / GSL.Z(1,1)).println(); // (0.50-0.50i) // inversion
(-GSL.Z(3,4)).println(); // (-3.00-4.00i)
(-GSL.Z(3,4)).println(); // (-3.00-4.00i)
GSL.Z(3,4).conjugate().println(); // (3.00-4.00i)</lang>
GSL.Z(3,4).conjugate().println(); // (3.00-4.00i)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 5,569: Line 5,569:


=={{header|zonnon}}==
=={{header|zonnon}}==
<lang zonnon>
<syntaxhighlight lang=zonnon>
module Numbers;
module Numbers;
type
type
Line 5,664: Line 5,664:
Writeln(~b);
Writeln(~b);
end Main.
end Main.
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 5,677: Line 5,677:
=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
{{trans|BBC BASIC}}
{{trans|BBC BASIC}}
<lang zxbasic>5 LET complex=2: LET r=1: LET i=2
<syntaxhighlight lang=zxbasic>5 LET complex=2: LET r=1: LET i=2
10 DIM a(complex): LET a(r)=1.0: LET a(i)=1.0
10 DIM a(complex): LET a(r)=1.0: LET a(i)=1.0
20 DIM b(complex): LET b(r)=PI: LET b(i)=1.2
20 DIM b(complex): LET b(r)=PI: LET b(i)=1.2
Line 5,700: Line 5,700:
1000 IF o(i)>=0 THEN PRINT o(r);" + ";o(i);"i": RETURN
1000 IF o(i)>=0 THEN PRINT o(r);" + ";o(i);"i": RETURN
1010 PRINT o(r);" - ";-o(i);"i": RETURN
1010 PRINT o(r);" - ";-o(i);"i": RETURN
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Result of addition is:
<pre>Result of addition is: