Arithmetic/Complex: Difference between revisions
m
→{{header|Icon}} and {{header|Unicon}}
(→{{header|Smalltalk}}: more examples involving fractions) |
|||
(34 intermediate revisions by 19 users not shown) | |||
Line 29:
{{trans|Python}}
<
V z2 = 1.5 + 1.5i
print(z1 + z2)
Line 40:
print(z1 ^ z2)
print(z1.real)
print(z1.imag)</
{{out}}
Line 54:
1.5
3
</pre>
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
DEFINE R_="+0"
DEFINE I_="+6"
TYPE Complex=[CARD cr1,cr2,cr3,ci1,ci2,ci3]
BYTE FUNC Positive(REAL POINTER x)
BYTE ARRAY tmp
tmp=x
IF (tmp(0)&$80)=$00 THEN
RETURN (1)
FI
RETURN (0)
PROC PrintComplex(Complex POINTER x)
PrintR(x R_)
IF Positive(x I_) THEN
Put('+)
FI
PrintR(x I_) Put('i)
RETURN
PROC PrintComplexXYZ(Complex POINTER x,y,z CHAR ARRAY s)
Print("(") PrintComplex(x)
Print(") ") Print(s)
Print(" (") PrintComplex(y)
Print(") = ") PrintComplex(z)
PutE()
RETURN
PROC PrintComplexXY(Complex POINTER x,y CHAR ARRAY s)
Print(s)
Print("(") PrintComplex(x)
Print(") = ") PrintComplex(y)
PutE()
RETURN
PROC ComplexAdd(Complex POINTER x,y,res)
RealAdd(x R_,y R_,res R_) ;res.r=x.r+y.r
RealAdd(x I_,y I_,res I_) ;res.i=x.i+y.i
RETURN
PROC ComplexSub(Complex POINTER x,y,res)
RealSub(x R_,y R_,res R_) ;res.r=x.r-y.r
RealSub(x I_,y I_,res I_) ;res.i=x.i-y.i
RETURN
PROC ComplexMult(Complex POINTER x,y,res)
REAL tmp1,tmp2
RealMult(x R_,y R_,tmp1) ;tmp1=x.r*y.r
RealMult(x I_,y I_,tmp2) ;tmp2=x.i*y.i
RealSub(tmp1,tmp2,res R_) ;res.r=x.r*y.r-x.i*y.i
RealMult(x R_,y I_,tmp1) ;tmp1=x.r*y.i
RealMult(x I_,y R_,tmp2) ;tmp2=x.i*y.r
RealAdd(tmp1,tmp2,res I_) ;res.i=x.r*y.i+x.i*y.r
RETURN
PROC ComplexDiv(Complex POINTER x,y,res)
REAL tmp1,tmp2,tmp3,tmp4
RealMult(x R_,y R_,tmp1) ;tmp1=x.r*y.r
RealMult(x I_,y I_,tmp2) ;tmp2=x.i*y.i
RealAdd(tmp1,tmp2,tmp3) ;tmp3=x.r*y.r+x.i*y.i
RealMult(y R_,y R_,tmp1) ;tmp1=y.r^2
RealMult(y I_,y I_,tmp2) ;tmp2=y.i^2
RealAdd(tmp1,tmp2,tmp4) ;tmp4=y.r^2+y.i^2
RealDiv(tmp3,tmp4,res R_) ;res.r=(x.r*y.r+x.i*y.i)/(y.r^2+y.i^2)
RealMult(x I_,y R_,tmp1) ;tmp1=x.i*y.r
RealMult(x R_,y I_,tmp2) ;tmp2=x.r*y.i
RealSub(tmp1,tmp2,tmp3) ;tmp3=x.i*y.r-x.r*y.i
RealDiv(tmp3,tmp4,res I_) ;res.i=(x.i*y.r-x.r*y.i)/(y.r^2+y.i^2)
RETURN
PROC ComplexNeg(Complex POINTER x,res)
REAL neg
ValR("-1",neg) ;neg=-1
RealMult(x R_,neg,res R_) ;res.r=-x.r
RealMult(x I_,neg,res I_) ;res.r=-x.r
RETURN
PROC ComplexInv(Complex POINTER x,res)
REAL tmp1,tmp2,tmp3
RealMult(x R_,x R_,tmp1) ;tmp1=x.r^2
RealMult(x I_,x I_,tmp2) ;tmp2=x.i^2
RealAdd(tmp1,tmp2,tmp3) ;tmp3=x.r^2+x.i^2
RealDiv(x R_,tmp3,res R_) ;res.r=x.r/(x.r^2+x.i^2)
ValR("-1",tmp1) ;tmp1=-1
RealMult(x I_,tmp1,tmp2) ;tmp2=-x.i
RealDiv(tmp2,tmp3,res I_) ;res.i=-x.i/(x.r^2+x.i^2)
RETURN
PROC ComplexConj(Complex POINTER x,res)
REAL neg
ValR("-1",neg) ;neg=-1
RealAssign(x R_,res R_) ;res.r=x.r
RealMult(x I_,neg,res I_) ;res.i=-x.i
RETURN
PROC Main()
Complex x,y,res
IntToReal(5,x R_) IntToReal(3,x I_)
IntToReal(4,y R_) ValR("-3",y I_)
Put(125) PutE() ;clear screen
ComplexAdd(x,y,res)
PrintComplexXYZ(x,y,res,"+")
ComplexSub(x,y,res)
PrintComplexXYZ(x,y,res,"-")
ComplexMult(x,y,res)
PrintComplexXYZ(x,y,res,"*")
ComplexDiv(x,y,res)
PrintComplexXYZ(x,y,res,"/")
ComplexNeg(y,res)
PrintComplexXY(y,res," -")
ComplexInv(y,res)
PrintComplexXY(y,res," 1 / ")
ComplexConj(y,res)
PrintComplexXY(y,res," conj")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Complex.png Screenshot from Atari 8-bit computer]
<pre>
(5+3i) + (4-3i) = 9+0i
(5+3i) - (4-3i) = 1+6i
(5+3i) * (4-3i) = 29-3i
(5+3i) / (4-3i) = .44+1.08i
-(4-3i) = -4+3i
1 / (4-3i) = .16+.12i
conj(4-3i) = 4+3i
</pre>
=={{header|Ada}}==
<
with Ada.Text_IO.Complex_IO;
Line 103 ⟶ 252:
Put("Conjugate(-A) = ");
C := Conjugate (C); Put(C);
end Complex_Operations;</
=={{header|ALGOL 68}}==
Line 110 ⟶ 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]}}
{{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}}
<
FORMAT compl fmt = $g(-7,5)"⊥"g(-7,5)$;
Line 136 ⟶ 285:
);
compl operations
)</
{{out}}<pre>
Line 149 ⟶ 298:
=={{header|ALGOL W}}==
Complex is a built-in type in Algol W.
<
% show some complex arithmetic %
% returns c + d, using the builtin complex + operator %
Line 173 ⟶ 322:
write( "1/c : ", cInv( c ) );
write( "conj c : ", cConj( c ) )
end.</
{{out}}
<pre>
Line 186 ⟶ 335:
=={{header|APL}}==
<syntaxhighlight lang="text">
x←1j1 ⍝assignment
y←5.25j1.5
Line 197 ⟶ 346:
-x ⍝negation
¯1J¯1
</syntaxhighlight>
=={{header|App Inventor}}==
Line 203 ⟶ 352:
The linked image gives a few examples of complex arithmetic and a custom complex conjugate function.<br>
[https://lh4.googleusercontent.com/-4M57lWIh_r8/Uuqgoec-hrI/AAAAAAAAJ74/2oj_5eelUR4/w1197-h766-no/Capture.PNG View the blocks and app screen...]
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">a: to :complex [1 1]
b: to :complex @[pi 1.2]
print ["a:" a]
print ["b:" b]
print ["a + b:" a + b]
print ["a * b:" a * b]
print ["1 / a:" 1 / a]
print ["neg a:" neg a]
print ["conj a:" conj a]</syntaxhighlight>
{{out}}
<pre>a: 1.0+1.0i
b: 3.141592653589793+1.2i
a + b: 4.141592653589793+2.2i
a * b: 1.941592653589793+4.341592653589793i
1 / a: 0.5-0.5i
neg a: -1.0-1.0i
conj a: 1.0-1.0i</pre>
=={{header|AutoHotkey}}==
contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276431.html#276431 forum]
<
MsgBox % Cstr(C) ; 1 + i*1
Cneg(C,C)
Line 252 ⟶ 425:
NumPut( Cre(A)/d,C,0,"double")
NumPut(-Cim(A)/d,C,8,"double")
}</
=={{header|AWK}}==
contributed by af
<syntaxhighlight lang="awk"># simulate a struct using associative arrays
function complex(arr, re, im) {
arr["re"] = re
arr["im"] = im
}
function re(cmplx) {
return cmplx["re"]
}
function im(cmplx) {
return cmplx["im"]
}
function printComplex(cmplx) {
print re(cmplx), im(cmplx)
}
function abs2(cmplx) {
return re(cmplx) * re(cmplx) + im(cmplx) * im(cmplx)
}
function abs(cmplx) {
return sqrt(abs2(cmplx))
}
function add(res, cmplx1, cmplx2) {
complex(res, re(cmplx1) + re(cmplx2), im(cmplx1) + im(cmplx2))
}
function mult(res, cmplx1, cmplx2) {
complex(res, re(cmplx1) * re(cmplx2) - im(cmplx1) * im(cmplx2), re(cmplx1) * im(cmplx2) + im(cmplx1) * re(cmplx2))
}
function scale(res, cmplx, scalar) {
complex(res, re(cmplx) * scalar, im(cmplx) * scalar)
}
function negate(res, cmplx) {
scale(res, cmplx, -1)
}
function conjugate(res, cmplx) {
complex(res, re(cmplx), -im(cmplx))
}
function invert(res, cmplx) {
conjugate(res, cmplx)
scale(res, res, 1 / abs(cmplx))
}
BEGIN {
complex(i, 0, 1)
mult(i, i, i)
printComplex(i)
}</syntaxhighlight>
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
<
real AS DOUBLE
imag AS DOUBLE
END TYPE
DECLARE SUB suma (a AS complex, b AS complex, c AS complex)
DECLARE SUB rest (a AS complex, b AS complex, c AS complex)
DECLARE SUB mult (a AS complex, b AS complex, c AS complex)
DECLARE SUB
DECLARE SUB neg (a AS complex, b AS complex)
DECLARE SUB inv (a AS complex, b AS complex)
DECLARE SUB conj (a AS complex, b AS complex)
CLS
DIM x AS complex
Line 272 ⟶ 509:
y.real = 2
y.imag = 2
PRINT
PRINT " e y = "; y.real; "+"; y.imag; "i"
PRINT
CALL suma(x, y, z)
PRINT "x + y = "; z.real; "+"; z.imag; "i"
CALL rest(x, y, z)
PRINT "x - y = "; z.real; "+"; z.imag; "i"
CALL mult(x, y, z)
PRINT "x * y = "; z.real; "+"; z.imag; "i"
CALL
PRINT "x / y = "; z.real; "+"; z.imag; "i"
CALL neg(x, z)
PRINT " -x = "; z.real; "+"; z.imag; "i"
CALL inv(x, z)
PRINT "1 / x = "; z.real; "+"; z.imag; "i"
CALL conj(x, z)
PRINT " x* = "; z.real; "+"; z.imag; "i"
END
SUB suma (a AS complex, b AS complex, c AS complex)
c.real = a.real + b.real
c.imag = a.imag + b.imag
Line 301 ⟶ 548:
b.real = -a.real
b.imag = -a.imag
END SUB
SUB conj (a AS complex, b AS complex)
b.real = a.real
b.imag = -a.imag
END SUB
SUB divi (a AS complex, b AS complex, c AS complex)
c.real = ((a.real * b.real + b.imag * a.imag) / (b.real ^ 2 + b.imag ^ 2))
c.imag = ((a.imag * b.real - a.real * b.imag) / (b.real ^ 2 + b.imag ^ 2))
END SUB
SUB rest (a AS complex, b AS complex, c AS complex)
c.real = a.real - b.real
c.imag = a.imag - b.imag
END SUB
</syntaxhighlight>
{{out}}
<pre>Siendo
e y = 5+ 2i
x + y = 6 + 5 i
x - y = -4 + 1 i
x * y = -1 + 17 i
x / y = .3793103448275862 + .4482758620689655 i
-x = -1 +-3 i
1 / x = .1 +-.3 i
x* = 1 +-3 i</pre>
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
DIM a{} = Complex{} : a.r = 1.0 : a.i = 1.0
Line 349 ⟶ 618:
DEF FNcomplexshow(src{})
IF src.i >= 0 THEN = STR$(src.r) + " + " +STR$(src.i) + "i"
= STR$(src.r) + " - " + STR$(-src.i) + "i"</
{{out}}
<pre>Result of addition is 4.14159265 + 2.2i
Line 358 ⟶ 627:
=={{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.
<
& ( multiply
= a b.!arg:(?a,?b)&1+!a*!b+-1
Line 385 ⟶ 654:
& out
$ ("sin$x minus conjugate sin$x =" sin$x+negate$(conjugate$(sin$x)))
& done;</
{{out}}
<pre>(a+i*b)+(a+i*b) = 2*a+2*i*b
Line 400 ⟶ 669:
{{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]
<
#include <stdio.h>
Line 431 ⟶ 700:
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
}</
{{works with|C89}}
User-defined type:
<
double real;
double imag;
Line 495 ⟶ 764:
printf("\n-a="); put(neg(a));
printf("\nconj a="); put(conj(a)); printf("\n");
}</
=={{header|C sharp|C#}}==
{{works with|C sharp|C#|4.0}}
<
{
using System;
Line 515 ⟶ 784:
}
}
}</
{{works with|C sharp|C#|1.2}}
<
public struct ComplexNumber
Line 721 ⟶ 990:
Console.WriteLine(ComplexMath.Power(j, 0) == 1.0);
}
}</
=={{header|C++}}==
<
#include <complex>
using std::complex;
Line 742 ⟶ 1,011:
// conjugate
std::cout << std::conj(a) << std::endl;
}</
=={{header|Clojure}}==
Line 748 ⟶ 1,017:
Therefore, we use defrecord and the multimethods in
clojure.algo.generic.arithmetic to make a Complex number type.
<
(:require [clojure.algo.generic.arithmetic :as ga])
(:import [java.lang Number]))
Line 785 ⟶ 1,054:
(let [m (+ (* r r) (* i i))]
(->Complex (/ r m) (- (/ i m)))))
</syntaxhighlight>
=={{header|COBOL}}==
Line 792 ⟶ 1,061:
===.NET Complex class===
{{trans|C#}}
<
$SET ILUSING "System"
$SET ILUSING "System.Numerics"
Line 805 ⟶ 1,074:
end-perform
end method.
end class.</
===Implementation===
<
class-id Prog.
method-id. Main static.
Line 905 ⟶ 1,174:
end operator.
end class.</
=={{header|CoffeeScript}}==
<
# create an immutable Complex type
class Complex
Line 969 ⟶ 1,238:
quotient = product.times inverse
console.log "(#{product}) / (#{b}) = #{quotient}"
</syntaxhighlight>
{{out}}
Line 986 ⟶ 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:
<
#C(0.0 1.0)
> (expt #c(0 1) 2)
-1</
Here are some arithmetic operations on complex numbers:
<
#C(1 1)
Line 1,010 ⟶ 1,279:
> (conjugate #c(1 1))
#C(1 -1)</
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.
<
#C(64 3/4)
Line 1,021 ⟶ 1,290:
> (imagpart (complex 0 pi))
3.141592653589793d0</
=={{header|Component Pascal}}==
BlackBox Component Builder
<
MODULE Complex;
IMPORT StdLog;
Line 1,112 ⟶ 1,381:
END Complex.
</syntaxhighlight>
Execute: ^Q Complex.Do<br/>
{{out}}
Line 1,128 ⟶ 1,397:
=={{header|D}}==
Built-in complex numbers are now deprecated in D, to simplify the language.
<
void main() {
Line 1,138 ⟶ 1,407:
writeln(1.0 / x); // inversion
writeln(-x); // negation
}</
{{out}}
<pre>4.14159+2.2i
Line 1,146 ⟶ 1,415:
=={{header|Dart}}==
<
class complex {
Line 1,198 ⟶ 1,467:
}
</syntaxhighlight>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.VarCmplx}}
<syntaxhighlight lang="delphi">
program Arithmetic_Complex;
Line 1,229 ⟶ 1,498:
Readln;
end.</
{{out}}
<pre>(5 + 3i) + (0,5 + 6i) = 5,5 + 9i
Line 1,238 ⟶ 1,507:
=={{header|EchoLisp}}==
Complex numbers are part of the language. No special library is needed.
<
(define a 42+666i) → a
(define b 1+i) → b
Line 1,249 ⟶ 1,518:
(magnitude b) → 1.4142135623730951 ; = sqrt(2)
(exp (* I PI)) → -1+0i ; Euler = e^(I*PI) = -1
</syntaxhighlight>
=={{header|Elixir}}==
<
import Kernel, except: [abs: 1, div: 2]
Line 1,336 ⟶ 1,605:
end
Complex.task</
{{out}}
Line 1,353 ⟶ 1,622:
=={{header|Erlang}}==
<
%% Author: Abhay Jain
Line 1,410 ⟶ 1,679:
true ->
io:format("Ans = ~p+~pi~n", [A#complex.real, A#complex.img])
end. </
{{out}}
<
Ans = -1+17i
Ans = -1-3i
Ans = 0.1-0.3i
Ans = 1-3i</
=={{header|ERRE}}==
<syntaxhighlight lang="text">
PROGRAM COMPLEX_ARITH
Line 1,468 ⟶ 1,737:
PRINT(Z.REAL#;" + ";Z.IMAG#;"i")
END PROGRAM
</syntaxhighlight>
Note: Adapted from QuickBasic source code
{{out}}
Line 1,478 ⟶ 1,747:
=={{header|Euler Math Toolbox}}==
<syntaxhighlight lang="euler math toolbox">
>a=1+4i; b=5-3i;
>a+b
Line 1,492 ⟶ 1,761:
>conj(a)
1-4i
</syntaxhighlight>
=={{header|Euphoria}}==
<
type complex(sequence s)
return length(s) = 2 and atom(s[REAL]) and atom(s[IMAG])
Line 1,552 ⟶ 1,821:
printf(1,"a*b = %s\n",{scomplex(mult(a,b))})
printf(1,"1/a = %s\n",{scomplex(inv(a))})
printf(1,"-a = %s\n",{scomplex(neg(a))})</
{{out}}
Line 1,566 ⟶ 1,835:
C1:
<
=IMSUM(A1;B1)
</syntaxhighlight>
D1:
<
=IMPRODUCT(A1;B1)
</syntaxhighlight>
E1:
<
=IMSUB(0;D1)
</syntaxhighlight>
F1:
<
=IMDIV(1;E28)
</syntaxhighlight>
G1:
<
=IMCONJUGATE(C28)
</syntaxhighlight>
E1 will have the negation of D1's value
<syntaxhighlight lang="text">
1+2i 3+5i 4+7i -7+11i 7-11i 0,0411764705882353+0,0647058823529412i 4-7i
</syntaxhighlight>
=={{header|F Sharp|F#}}==
Entered into an interactive session to show the results:
<
> open Microsoft.FSharp.Math;;
Line 1,644 ⟶ 1,913:
i = -1.0;
r = -1.0;}
</syntaxhighlight>
=={{header|Factor}}==
<
C{ 1 2 } C{ 0.9 -2.78 } {
Line 1,659 ⟶ 1,928:
C{ 1 2 } {
[ neg . ] ! negation
[
[ conjugate . ] ! complex conjugate
[ sin . ] ! sine
[ log . ] ! natural logarithm
[ sqrt . ] ! square root
} cleave</
=={{header|Forth}}==
{{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".
<
S" complex.fs" REQUIRED
Line 1,681 ⟶ 1,950:
1e 0e zconstant 1+0i
1+0i x z@ z/ z.
x z@ znegate z.</
=={{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:
<
complex :: a = (5,3), b = (0.5, 6.0) ! complex initializer
complex :: absum, abprod, aneg, ainv
Line 1,693 ⟶ 1,962:
aneg = -a
ainv = 1.0 / a
end program cdemo</
And, although you did not ask, here are demonstrations of some other common complex number operations
<
complex :: a = (5,3), b = (0.5, 6) ! complex initializer
real, parameter :: pi = 3.141592653589793 ! The constant "pi"
Line 1,723 ⟶ 1,992:
! useful for FFT calculations, among other things
unit_circle = exp(2*i*pi/n * (/ (j, j=0, n-1) /) )
end program cdemo2</
=={{header|FreeBASIC}}==
<
Type Complex
Line 1,790 ⟶ 2,059:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,804 ⟶ 2,073:
x* = 1-3j
</pre>
=={{header|Free Pascal}}==
FreePascal has a complex units. Example of usage:
<syntaxhighlight lang="pascal">Program ComplexDemo;
uses
ucomplex;
var
a, b, absum, abprod, aneg, ainv, acong: complex;
function complex(const re, im: real): ucomplex.complex; overload;
begin
complex.re := re;
complex.im := im;
end;
begin
a := complex(5, 3);
b := complex(0.5, 6.0);
absum := a + b;
writeln ('(5 + i3) + (0.5 + i6.0): ', absum.re:3:1, ' + i', absum.im:3:1);
abprod := a * b;
writeln ('(5 + i3) * (0.5 + i6.0): ', abprod.re:5:1, ' + i', abprod.im:4:1);
aneg := -a;
writeln ('-(5 + i3): ', aneg.re:3:1, ' + i', aneg.im:3:1);
ainv := 1.0 / a;
writeln ('1/(5 + i3): ', ainv.re:3:1, ' + i', ainv.im:3:1);
acong := cong(a);
writeln ('conj(5 + i3): ', acong.re:3:1, ' + i', acong.im:3:1);
end.
</syntaxhighlight>
=={{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.
<
add[x,y] := x + y
multiply[x,y] := x * y
Line 1,821 ⟶ 2,122:
println["1/$a = " + invert[a]]
println["conjugate[$a] = " + conjugate[a]]
</syntaxhighlight>
{{out}}
Line 1,834 ⟶ 2,135:
=={{header|Futhark}}==
{{incorrect|Futhark|Futhark's syntax has changed, so "fun" should be "let"}}
<syntaxhighlight lang="futhark">
type complex = (f64,f64)
Line 1,862 ⟶ 2,163:
else if o == 3 then complexNeg a
else complexConj a
</syntaxhighlight>
=={{header|GAP}}==
<
# E(n) is an nth primitive root of 1
i := Sqrt(-1);
Line 1,883 ⟶ 2,184:
# true
Sqrt(-3) in Cyclotomics;
# true</
=={{header|Go}}==
Go has complex numbers built in, with the complex conjugate in the standard library.
<
import (
Line 1,904 ⟶ 2,205:
fmt.Println("1 / a: ", 1/a)
fmt.Println("a̅: ", cmplx.Conj(a))
}</
{{out}}
<pre>
Line 1,918 ⟶ 2,219:
=={{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:
<
final Number real, imag
static final Complex i = [0,1] as Complex
Complex(Number r, Number i = 0) { (real, imag) = [r, i] }
Complex(Map that) { (real, imag) = [that.real ?: 0, that.imag ?: 0] }
Complex plus (Complex c) { [real + c.real, imag + c.imag] as Complex }
Complex plus (Number n) { [real + n, imag] as Complex }
Complex minus (Complex c) { [real - c.real, imag - c.imag] as Complex }
Complex minus (Number n) { [real - n, imag] as Complex }
Complex multiply (Complex c) { [real*c.real - imag*c.imag , imag*c.real + real*c.imag] as Complex }
Complex multiply (Number n) { [real*n , imag*n] as Complex }
Complex div (Complex c) { this * c.recip() }
Complex div (Number n) { this * (1/n) }
Complex negative () { [-real, -imag] as Complex }
/** the complex conjugate of this complex number. Overloads the bitwise complement (~) operator. */
Complex bitwiseNegate () { [real, -imag] as Complex }
/** the magnitude of this complex number. */
// could also use Math.sqrt( (this * (~this)).real )
Line 1,949 ⟶ 2,250:
/** the magnitude of this complex number. */
Number abs() { this.abs }
/** the reciprocal of this complex number. */
Complex getRecip() { (~this) / (ρ**2) }
/** the reciprocal of this complex number. */
Complex recip() { this.recip }
/** derived polar angle θ (theta) for polar form. Normalized to 0 ≤ θ < 2π. */
Number getTheta() {
Line 1,962 ⟶ 2,263:
/** derived polar angle θ (theta) for polar form. Normalized to 0 ≤ θ < 2π. */
Number getΘ() { this.theta } // this is greek uppercase theta
/** derived polar magnitude ρ (rho) for polar form. */
Number getRho() { this.abs }
/** derived polar magnitude ρ (rho) for polar form. */
Number getΡ() { this.abs } // this is greek uppercase rho, not roman P
/** Runs Euler's polar-to-Cartesian complex conversion,
* converting [ρ, θ] inputs into a [real, imag]-based complex number */
Line 1,973 ⟶ 2,274:
[ρ * Math.cos(θ), ρ * Math.sin(θ)] as Complex
}
/** Creates new complex with same magnitude ρ, but different angle θ */
Complex withTheta(Number θ) { fromPolar(this.rho, θ) }
/** Creates new complex with same magnitude ρ, but different angle θ */
Complex withΘ(Number θ) { fromPolar(this.rho, θ) }
/** Creates new complex with same angle θ, but different magnitude ρ */
Complex withRho(Number ρ) { fromPolar(ρ, this.θ) }
/** Creates new complex with same angle θ, but different magnitude ρ */
Complex withΡ(Number ρ) { fromPolar(ρ, this.θ) } // this is greek uppercase rho, not roman P
static Complex exp(Complex c) { fromPolar(Math.exp(c.real), c.imag) }
static Complex log(Complex c) { [Math.log(c.rho), c.theta] as Complex }
Complex power(Complex c) {
(this == zero && c !=
? zero \
: c == 1 \
? this \
: exp( log(this) * c )
}
Complex power(Number n) { this ** ([n, 0] as Complex) }
boolean equals(that) {
that != null && (that instanceof Complex \
Line 2,003 ⟶ 2,305:
: that instanceof Number && [this.real, this.imag] == [that, 0])
}
int hashCode() { [real, imag].hashCode() }
String toString() {
def realPart = "${real}"
Line 2,017 ⟶ 2,319:
: realPart + (imag > 0 ? " + " : " - ") + imagPart
}
}</
The following ''ComplexCategory'' class allows for modification of regular ''Number'' behavior when interacting with ''Complex''.
<
class ComplexCategory {
static Complex getI (Number a) { [0, a] as Complex }
static Complex plus (Number a, Complex b) { b + a }
static Complex minus (Number a, Complex b) { -b + a }
Line 2,030 ⟶ 2,332:
static Complex div (Number a, Complex b) { ([a] as Complex) / b }
static Complex power (Number a, Complex b) { ([a] as Complex) ** b }
static <N extends Number,T> T asType (
type == Complex \
? [a as Number] as Complex
: DefaultGroovyMethods.asType(a, type)
}
}</
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):
<
Number.metaClass.mixin ComplexCategory
Integer.metaClass.mixin ComplexCategory
def ε = 0.000000001 // tolerance (epsilon): acceptable "wrongness" to account for rounding error
println 'Demo 1: functionality as requested'
def a = [5,3] as Complex
Line 2,055 ⟶ 2,358:
def b = [0.5,6] as Complex
println 'b == ' + b
println "a + b == (${a}) + (${b}) == " + (a + b)
println "a * b == (${a}) * (${b}) == " + (a * b)
Line 2,064 ⟶ 2,367:
println "a * 1/a == " + (a * a.recip)
println()
println 'Demo 2: other functionality not requested, but important for completeness'
def c = 10
Line 2,091 ⟶ 2,394:
println 'a.θ == ' + a.θ
println '~a (conjugate) == ' + ~a
def ρ = 10
def π = Math.PI
def n = 3
def θ = π / n
def fromPolar1 = fromPolar(ρ, θ) // direct polar-to-cartesian conversion
def fromPolar2 = exp(θ.i) * ρ // Euler's equation
Line 2,102 ⟶ 2,405:
println " == 10*0.5 + i*10*√(3/4) == " + fromPolar1
println "ρ*exp(i*θ) == ${ρ}*exp(i*π/${n}) == " + fromPolar2
assert (fromPolar1 - fromPolar2).abs < ε</
{{out}}
Line 2,123 ⟶ 2,426:
a ** 2 == a * a == 16.000000000000004 + 30.000000000000007i
0.9 ** b == 0.7653514303676113 - 0.5605686291920475i
a ** b == (5 + 3i) ** (0.5 + 6i) == -0.
a.real == 5
a.imag == 3
Line 2,135 ⟶ 2,438:
== 10*0.5 + i*10*√(3/4) == 5.000000000000001 + 8.660254037844386i
ρ*exp(i*θ) == 10*exp(i*π/3) == 5.000000000000001 + 8.660254037844386i</pre>
=={{header|Hare}}==
<syntaxhighlight lang="hare">use fmt;
use math::complex::{c128,addc128,mulc128,divc128,negc128,conjc128};
export fn main() void = {
let x: c128 = (1.0, 1.0);
let y: c128 = (3.14159265, 1.2);
// addition
let (re, im) = addc128(x, y);
fmt::printfln("{} + {}i", re, im)!;
// multiplication
let (re, im) = mulc128(x, y);
fmt::printfln("{} + {}i", re, im)!;
// inversion
let (re, im) = divc128((1.0, 0.0), x);
fmt::printfln("{} + {}i", re, im)!;
// negation
let (re, im) = negc128(x);
fmt::printfln("{} + {}i", re, im)!;
// conjugate
let (re, im) = conjc128(x);
fmt::printfln("{} + {}i", re, im)!;
};</syntaxhighlight>
=={{header|Haskell}}==
Line 2,141 ⟶ 2,469:
have ''Complex Integer'' for the Gaussian Integers, ''Complex Float'', ''Complex Double'', etc. The operations are just the usual overloaded numeric operations.
<
main = do
Line 2,154 ⟶ 2,482:
putStrLn $ "Negate: " ++ show (-a)
putStrLn $ "Inverse: " ++ show (recip a)
putStrLn $ "Conjugate:" ++ show (conjugate a)</
{{out}}
Line 2,165 ⟶ 2,493:
Inverse: 0.2 :+ (-0.4)
Conjugate:1.0 :+ (-2.0)</pre>
=={{header|Icon}} and {{header|Unicon}}==
Icon doesn't provide native support for complex numbers. Support is included in the IPL.
Note: see the [[Arithmetic/Complex#Unicon|Unicon]] section below for a Unicon-specific solution.
<syntaxhighlight lang="icon">procedure main()
SetupComplex()
Line 2,191 ⟶ 2,518:
write("abs(a) := ", cpxabs(a))
write("neg(1) := ", cpxstr(cpxneg(1)))
end</
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}}
[http://www.cs.arizona.edu/icon/library/src/procs/complex.icn provides complex number support] supplemented by the code below.
<syntaxhighlight lang="icon">
link complex # for complex number support
Line 2,223 ⟶ 2,550:
denom := z.rpart ^ 2 + z.ipart ^ 2
return complex(z.rpart / denom, z.ipart / denom)
end</
To take full advantage of the overloaded 'complex' procedure,
the other cpxxxx procedures would need to be rewritten or overloaded.
Line 2,249 ⟶ 2,576:
<tt>complex</tt> (and <tt>dcomplex</tt> for double-precision) is a built-in data type in IDL:
<
y=complex(!pi,1.2)
print,x+y
Line 2,258 ⟶ 2,585:
( -1.00000, -1.00000)
print,1/x
( 0.500000, -0.500000)</
=={{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.
<
y=: 3.14159j1.2
x+y NB. addition
Line 2,274 ⟶ 2,601:
+x NB. (complex) conjugation
1j_1
</syntaxhighlight>
=={{header|Java}}==
<
public final double real;
public final double imag;
Line 2,328 ⟶ 2,655:
System.out.println(a.conj());
}
}</
=={{header|JavaScript}}==
<
this.r = r;
this.i = i;
Line 2,385 ⟶ 2,712:
Complex.prototype.getMod = function() {
return Math.sqrt( Math.pow(this.r,2) , Math.pow(this.i,2) )
}</
=={{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.
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 imag(z): if (z|type) == "number" then 0 else z[1] end;
Line 2,412 ⟶ 2,739:
x[0] * y[1] + x[1] * y[0]]
end;
def multiply: reduce .[] as $x (1; multiply(.; $x));
def negate(x): multiply(-1; x);
Line 2,451 ⟶ 2,780:
;
test( [1,1]; [0,1] )</
{{Out}}
<
"x = [1,1]"
"y = [0,1]"
Line 2,462 ⟶ 2,791:
"conj(x): [1,-1]"
"(x/y)*y: [1,1]"
"e^iπ: [-1,1.2246467991473532e-16]"</
=={{header|Julia}}==
Julia has built-in support for complex arithmetic with arbitrary real types.
<
julia> z2 = 1.5 + 1.5im
julia> z1 + z2
Line 2,487 ⟶ 2,816:
1.5
julia> imag(z1)
3.0</
=={{header|Kotlin}}==
<
operator fun plus(other: Complex) = Complex(real + other.real, imag + other.imag)
Line 2,528 ⟶ 2,857:
println("1 / x = ${x.inv()}")
println("x* = ${x.conj()}")
}</
{{out}}
Line 2,544 ⟶ 2,873:
=={{header|Lambdatalk}}==
<
{require lib_complex}
Line 2,568 ⟶ 2,897:
{C.mul {z1} {z2}} -> (0 3)
{C.div {z1} {z2}} -> (0.6666666666666667 0)
</syntaxhighlight>
=={{header|Lang}}==
<syntaxhighlight lang="lang">
fp.cprint = ($z) -> fn.printf(%.3f%+.3fi%n, fn.creal($z), fn.cimag($z))
$a = fn.complex(1.5, 3)
$b = fn.complex(1.5, 1.5)
fn.print(a =\s)
fp.cprint($a)
fn.print(b =\s)
fp.cprint($b)
# Addition
fn.print(a + b =\s)
fp.cprint(fn.cadd($a, $b))
# Multiplication
fn.print(a * b =\s)
fp.cprint(fn.cmul($a, $b))
# Inversion
fn.print(1/a =\s)
fp.cprint(fn.cdiv(fn.complex(1, 0), $a))
# Negation
fn.print(-a =\s)
fp.cprint(fn.cinv($a))
# Conjugate
fn.print(conj(a) =\s)
fp.cprint(fn.conj($a))
</syntaxhighlight>
{{out}}
<pre>
a = 1.500+3.000i
b = 1.500+1.500i
a + b = 3.000+4.500i
a * b = -2.250+6.750i
1/a = 0.133-0.267i
-a = -1.500-3.000i
conj(a) = 1.500-3.000i
</pre>
=={{header|LFE}}==
Line 2,575 ⟶ 2,948:
A convenient data structure for a complex number is the record:
<
(defrecord complex
real
img)
</syntaxhighlight>
Here are the required functions:
<
(defun add
(((match-complex real r1 img i1)
Line 2,601 ⟶ 2,974:
(defun inv (cmplx)
(div (conj cmplx) (modulus cmplx)))
</syntaxhighlight>
Bonus:
<
(defun conj
(((match-complex real r img i))
(new r (* -1 i))))
</syntaxhighlight>
The functions above are built using the following supporting functions:
<
(defun new (r i)
(make-complex real r img i))
Line 2,626 ⟶ 2,999:
(/ (complex-img c3) denom)))))
</syntaxhighlight>
Finally, we have some functions for use in the conversion and display of our complex number data structure:
<
(defun ->str
(((match-complex real r img i)) (when (>= i 0))
Line 2,642 ⟶ 3,015:
(defun print (cmplx)
(io:format (++ (->str cmplx) "~n")))
</syntaxhighlight>
Usage is as follows:
Line 2,669 ⟶ 3,042:
=={{header|Liberty BASIC}}==
<
print " Adding"
Line 2,719 ⟶ 3,092:
D =ar^2 +ai^2
cinv$ =complex$( ar /D , 0 -ai /D )
end function</
=={{header|Lua}}==
<
--defines addition, subtraction, negation, multiplication, division, conjugation, norms, and a conversion to strgs.
Line 2,755 ⟶ 3,128:
print("|" .. i .. "| = " .. math.sqrt(i.norm))
print(i .. "* = " .. i.conj)
</syntaxhighlight>
=={{header|Maple}}==
Line 2,761 ⟶ 3,134:
Maple has <code>I</code> (the square root of -1) built-in. Thus:
<
y := Pi+I*1.2;</
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:
<
==> (1 + I) (Pi + 1.2 I)
simplify(x*y);
==> 1.941592654 + 4.341592654 I</
Other than that, the task merely asks for
<
x*y;
-x;
1/x;</
=={{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:
<
y=3+4I
Line 2,790 ⟶ 3,163:
y^4 => -527 - 336 I
x^y => (1 + 2 I)^(3 + 4 I)
N[x^y] => 0.12901 + 0.0339241 I</
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!):
<
Sin Cos Tan Csc Sec Cot
ArcSin ArcCos ArcTan ArcCsc ArcSec ArcCot
Line 2,801 ⟶ 3,174:
Haversine InverseHaversine
Factorial Gamma PolyGamma LogGamma
Erf BarnesG Hyperfactorial Zeta ProductLog RamanujanTauL</
and many many more. The documentation states:
Line 2,809 ⟶ 3,182:
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".
<
a =
Line 2,867 ⟶ 3,240:
ans =
1.414213562373095</
=={{header|Maxima}}==
<
2*%i+5
Line 2,913 ⟶ 3,286:
imagpart(z1);
2</
=={{header|МК-61/52}}==
Line 2,924 ⟶ 3,297:
Division: С/П; multiplication: БП 36 С/П; addition: БП 54 С/П; subtraction: БП 63 С/П.
<syntaxhighlight lang="text">ПA С/П ПB С/П ПC С/П ПD С/П ИПC x^2
ИПD x^2 + П3 ИПA ИПC * ИПB ИПD *
+ ИП3 / П1 ИПB ИПC * ИПA ИПD *
Line 2,931 ⟶ 3,304:
+ П2 ИП1 С/П ИПB ИПD + П2 ИПA ИПC
+ ИП1 С/П ИПB ИПD - П2 ИПA ИПC -
П1 С/П</
=={{header|Modula-2}}==
<
IMPORT InOut;
Line 2,999 ⟶ 3,372:
NegComplex (z[0], z[2]); ShowComplex (" - z1", z[2]);
InOut.WriteLn
END complex.</
{{out}}
<pre>Enter two complex numbers : 5 3 0.5 6
Line 3,014 ⟶ 3,387:
{{trans|Java}}
This is a translation of the Java version, but it uses operator redefinition where possible.
<
class Complex
Line 3,069 ⟶ 3,442:
println a.inv()
println a * b
println a.conj()</
=={{header|Nemerle}}==
<
using System.Console;
using System.Numerics;
Line 3,097 ⟶ 3,470:
WriteLine(Conjugate(complex2).PrettyPrint());
}
}</
{{out}}
<pre>4.14159 + 2.2i
Line 3,106 ⟶ 3,479:
=={{header|Nim}}==
<
import complex
var a: Complex = (1.0,1.0)
Line 3,118 ⟶ 3,491:
echo("-a : " & $(-a))
</syntaxhighlight>
{{out}}
<pre>
Line 3,131 ⟶ 3,504:
=={{header|Oberon-2}}==
Oxford Oberon Compiler
<
MODULE Complex;
IMPORT Files,Out;
Line 3,217 ⟶ 3,590:
END Complex.
</syntaxhighlight>
{{out}}
<pre>
Line 3,232 ⟶ 3,605:
=={{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:
<
let print_complex z =
Line 3,244 ⟶ 3,617:
print_complex (inv a);
print_complex (neg a);
print_complex (conj a)</
Using [http://forge.ocamlcore.org/projects/pa-do/ Delimited Overloading], the syntax can be made closer to the usual one:
<
Complex.(
let print txt z = Printf.printf "%s = %s\n" txt (to_string z) in
Line 3,260 ⟶ 3,633:
print "a^b" (a**b);
Printf.printf "norm a = %g\n" (float(abs a));
)</
=={{header|Octave}}==
GNU Octave handles naturally complex numbers:
<
z2 = 1.5 + 1.5i;
disp(z1 + z2); % 3.0 + 4.5i
Line 3,277 ⟶ 3,650:
disp( imag(z1) ); % 3
disp( real(z2) ); % 1.5
%...</
=={{header|Oforth}}==
<
Complex method: re @re ;
Line 3,319 ⟶ 3,692:
Integer method: >complex self 0 Complex new ;
Float method: >complex self 0 Complex new ;</
Usage :
<
2 3 Complex new 1.2 >complex + .cr
2 3 Complex new 1.2 >complex * .cr
2 >complex 2 3 Complex new / .cr</
{{out}}
Line 3,339 ⟶ 3,712:
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`.
<
(define A 0+1i) ; manually entered numbers
(define B 1+0i)
Line 3,363 ⟶ 3,736:
(print "imaginary part of " C " is " (cdr C))
; <== imaginary part of 2/7-3i is -3
</syntaxhighlight>
=={{header|ooRexx}}==
<
c2 = .complex~new(3, 4)
r = 7
Line 3,502 ⟶ 3,875:
::method hashCode
expose r i
return r~hashcode~bitxor(i~hashcode)</
{{out}}
<pre>c1 = 1 + 2i
Line 3,523 ⟶ 3,896:
=={{header|OxygenBasic}}==
Implementation of a complex numbers class with arithmetical operations, and powers using DeMoivre's theorem (polar conversion).
<
'COMPLEX OPERATIONS
'=================
Line 3,656 ⟶ 4,029:
z1 = z1*z4
print "Z1 = "+z1.show 'RESULT 2.0, 1.0
</syntaxhighlight>
=={{header|PARI/GP}}==
To use, type, e.g., inv(3 + 7*I).
<
mult(a,b)=a*b;
neg(a)=-a;
inv(a)=1/a;</
=={{header|Pascal}}==
{{works with|Extended Pascal}}
The simple data type <tt>complex</tt> is part of Extended Pascal, ISO standard 10206.
<syntaxhighlight lang="pascal">program complexDemo(output);
const
{ I experienced some hiccups with -1.0 using GPC (GNU Pascal Compiler) }
negativeOne = -1.0;
type
line = string(80);
{ as per task requirements wrap arithmetic operations into separate functions }
begin
sum := x + y
end;
function product(protected x, y: complex): complex;
product := x * y
end;
negative := -x
inverse := x ** negativeOne
end;
{ only this function is not covered by Extended Pascal, ISO 10206 }
function conjugation(protected x: complex): complex;
begin
conjugation := cmplx(re(x), im(x) * negativeOne)
{ --- test suite ------------------------------------------------------------- }
function asString(protected x: complex): line;
const
totalWidth = 5;
fractionDigits = 2;
var
result: line;
begin
writeStr(result, '(', re(x):totalWidth:fractionDigits, ', ',
im(x):totalWidth:fractionDigits, ')');
asString := result
end;
{ === MAIN =================================================================== }
var
x: complex;
{ for demonstration purposes: how to initialize complex variables }
y: complex value cmplx(1.0, 4.0);
z: complex value polar(exp(1.0), 3.14159265358979);
begin
x := cmplx(-3, 2);
writeLn(asString(x), ' + ', asString(y), ' = ', asString(sum(x, y)));
writeLn(asString(x), ' * ', asString(z), ' = ', asString(product(x, z)));
writeLn;
writeLn(' −', asString(z), ' = ', asString(negative(z)));
writeLn(' inverse(', asString(z), ') = ', asString(inverse(z)));
writeLn(' conjugation(', asString(y), ') = ', asString(conjugation(y)));
end.</syntaxhighlight>
{{out}}
<pre>(-3.00, 2.00) + ( 1.00, 4.00) = (-2.00, 6.00)
(-3.00, 2.00) * (-2.72, 0.00) = ( 8.15, -5.44)
−(-2.72, 0.00) = ( 2.72, -0.00)
inverse((-2.72, 0.00)) = (-0.37, -0.00)
conjugation(( 1.00, 4.00)) = ( 1.00, -4.00)</pre>
The GPC, GNU Pascal Compiler, supports Extended Pascal’s <tt>complex</tt> data type and operations as shown.
Furthermore, the GPC defines a function <tt>conjugate</tt> so there is no need for writing such a custom function.
The PXSC, Pascal eXtensions for scientific computing, define a standard data type similar to [[#Free Pascal|Free Pascal’s]] <tt>ucomplex</tt> data type.
=={{header|Perl}}==
The <code>Math::Complex</code> module implements complex arithmetic.
<
my $a = 1 + 1*i;
my $b = 3.14159 + 1.25*i;
Line 3,777 ⟶ 4,130:
-$a, # negation
1 / $a, # multiplicative inverse
~$a; # complex conjugate</
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<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;">include</span> <span style="color: #004080;">complex</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #004080;">complex</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">complex_new</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">),</span> <span style="color: #000080;font-style:italic;">-- (or just {1,1})</span>
<span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">complex_new</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3.14159</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1.25</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">complex_new</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">d</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>
<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: #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;">"b = %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">complex_sprint</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</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;">"c = %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">complex_sprint</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</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;">"d = %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">complex_sprint</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</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+b = %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_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</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*b = %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_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</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;">"1/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_inv</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;">"c/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_div</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</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;">"c-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_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</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;">"d-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_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</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>
<!--</syntaxhighlight>-->
{{out}}
<pre>
a = 1+i
b = 3.14159+1.
c = 1
d = i
a+b = 4.14159+2.25i
a*b = 1.89159+4.39159i
1/a = 0.5-0.5i
c/a = 0.5-0.5i
c-a = -i
d-a = -1
-a = -1-i
conj a = 1-i
</pre>
=={{header|PicoLisp}}==
<
(de addComplex (A B)
Line 3,891 ⟶ 4,212:
(prinl "A*B = " (fmtComplex (mulComplex A B)))
(prinl "1/A = " (fmtComplex (invComplex A)))
(prinl "-A = " (fmtComplex (negComplex A))) )</
{{out}}
<pre>A = 1.00000+1.00000i
Line 3,901 ⟶ 4,222:
=={{header|PL/I}}==
<
/* In this example, the variables are floating-pint. */
/* For integer variables, change 'float' to 'fixed binary' */
Line 3,921 ⟶ 4,242:
/* As well, trigonometric functions may be used with complex */
/* numbers, such as SIN, COS, TAN, ATAN, and so on. */</
=={{header|Pop11}}==
Line 3,934 ⟶ 4,255:
'1 -: 3' is '1 - 3i' in mathematical notation.
<
a+b =>
a*b =>
Line 3,952 ⟶ 4,273:
a-a =>
a/b =>
a/a =></
=={{header|PostScript}}==
Complex numbers can be represented as 2 element vectors ( arrays ). Thus, a+bi can be written as [a b] in PostScript.
<syntaxhighlight lang="text">
%Adding two complex numbers
/addcomp{
Line 4,005 ⟶ 4,326:
}def
</syntaxhighlight>
=={{header|PowerShell}}==
===Implementation===
<syntaxhighlight lang="powershell">
class Complex {
[Double]$x
Line 4,049 ⟶ 4,370:
"1/`$m: $([complex]::show($m.inverse()))"
"conjugate `$m: $([complex]::show($m.conjugate()))"
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 4,061 ⟶ 4,382:
</pre>
===Library===
<syntaxhighlight lang="powershell">
function show([System.Numerics.Complex]$c) {
if(0 -le $c.Imaginary) {
Line 4,078 ⟶ 4,399:
"1/`$m: $(show ([System.Numerics.Complex]::Reciprocal($m)))"
"conjugate `$m: $(show ([System.Numerics.Complex]::Conjugate($m)))"
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 4,091 ⟶ 4,412:
=={{header|PureBasic}}==
<
real.d
imag.d
Line 4,155 ⟶ 4,476:
*c=Neg_Complex(a): ShowAndFree("-a", *c)
Print(#CRLF$+"Press ENTER to exit"):Input()
EndIf</
=={{header|Python}}==
<
>>> z2 = 1.5 + 1.5j
>>> z1 + z2
Line 4,181 ⟶ 4,502:
>>> z1.imag
3.0
>>> </
=={{header|R}}==
{{trans|Octave}}
<
z2 <- 1.5 + 1.5i
print(z1 + z2) # 3+4.5i
Line 4,198 ⟶ 4,519:
print(exp(z1)) # -4.436839+0.632456i
print(Re(z1)) # 1.5
print(Im(z1)) # 3</
=={{header|Racket}}==
<
#lang racket
Line 4,215 ⟶ 4,536:
(/ 1 a) ; reciprocal
(conjugate a) ; conjugation
</syntaxhighlight>
=={{header|Raku}}==
Line 4,221 ⟶ 4,542:
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku"
my $b = pi + 1.25i;
.say for $a + $b, $a * $b, -$a, 1 / $a, $a.conj;
.say for $a.abs, $a.sqrt, $a.re, $a.im;</
{{out}} (precision varies with different implementations):
<pre>
Line 4,241 ⟶ 4,562:
=={{header|REXX}}==
The REXX language has no complex type numbers, but most complex arithmetic functions can easily be written.
<
x = '(5,3i)' /*define X ─── can use I i J or j */
y = "( .5, 6j)" /*define Y " " " " " " " */
Line 4,263 ⟶ 4,584:
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$: parse arg r,c; _='['r; if c\=0 then _=_","c'j'; return _"]" /*uses j */</
'''output'''
<pre>
Line 4,277 ⟶ 4,598:
=={{header|RLaB}}==
<syntaxhighlight lang="rlab">
>> x = sqrt(-1)
0 + 1i
Line 4,286 ⟶ 4,607:
>> isreal(z)
1
</syntaxhighlight>
=={{header|RPL}}==
{{in}}
<pre>
(1.5,3) 'Z1' STO
(1.5,1.5) 'Z2' STO
Z1 Z2 +
Z1 Z2 -
Z1 Z2 *
Z1 Z2 /
Z1 NEG
Z1 CONJ
Z1 ABS
Z1 RE
Z1 IM
</pre>
{{out}}
<pre>
(3,4.5)
(0,1.5)
(-2.25,6.75)
(1.5,.5)
(-1.5,-3)
(1.5,-3)
63.4349488229
1.5
3
</pre>
=={{header|Ruby}}==
<
# Four ways to write complex numbers:
a = Complex(1, 1) # 1. call Kernel#Complex
Line 4,303 ⟶ 4,651:
puts 1.quo a # multiplicative inverse
puts a.conjugate # complex conjugate
puts a.conj # alias for complex conjugate</
''Notes:''
* All of these operations are safe with other numeric types. For example, <code>42.conjugate</code> returns 42.
<
puts 1.quo a # always works
puts 1.0 / a # works, but forces floating-point math
puts 1 / a # might truncate to integer</
=={{header|Rust}}==
<
use num::complex::Complex;
Line 4,329 ⟶ 4,677:
println!(" -a = {}", -a);
println!("conj(a) = {}", a.conj());
}</
=={{header|Scala}}==
Line 4,335 ⟶ 4,683:
Scala doesn't come with a Complex library, but one can be made:
<
package object ArithmeticComplex {
Line 4,369 ⟶ 4,717:
def fromPolar(rho:Double, theta:Double) = Complex(rho*math.cos(theta), rho*math.sin(theta))
}
}</
Usage example:
<
import org.rosettacode.ArithmeticComplex._
Line 4,399 ⟶ 4,747:
scala> -res6
res7: org.rosettacode.ArithmeticComplex.Complex = -0.2 + 0.4i
</syntaxhighlight>
=={{header|Scheme}}==
Line 4,405 ⟶ 4,753:
* 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
<
(define b 3.14159+1.25i)
Line 4,411 ⟶ 4,759:
(define c (* a b))
(define c (/ 1 a))
(define c (- a))</
=={{header|Seed7}}==
<
include "float.s7i";
include "complex.s7i";
Line 4,434 ⟶ 4,782:
# negation
writeln("-a=" <& -a digits 5);
end func;</
=={{header|Sidef}}==
<
var b = 3.14159:1.25 # Complex(3.14159, 1.25)
Line 4,449 ⟶ 4,797:
b.re, # real
b.im, # imaginary
].each { |c| say c }</
{{out}}
<pre>4.14159+2.25i
Line 4,463 ⟶ 4,811:
=={{header|Slate}}==
<
a: 1 + 1 i.
b: Pi + 1.2 i.
Line 4,473 ⟶ 4,821:
print: a abs.
print: a negated.
].</
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<
|a b|
a := 1 + 1 i.
Line 4,489 ⟶ 4,837:
a real displayNl.
a imaginary displayNl.
a negated displayNl.</
{{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
<
|a b|
a := 1 + 1i.
Line 4,508 ⟶ 4,856:
Transcript show:'a imaginary => '; showCR:a imaginary.
Transcript show:'a negated => '; showCR:a negated.
Transcript show:'a sqrt => '; showCR:a sqrt.
a2 := (1/2) + 1i.
b2 := (2/3) + 2i.
Line 4,515 ⟶ 4,863:
Transcript show:'a2*b2 => '; showCR:(a2 * b2).
Transcript show:'a2/b2 => '; showCR:(a2 / b2).
Transcript show:'a2 reciprocal => '; showCR:a2 reciprocal.</syntaxhighlight>
{{out}}
<pre>a => (1+1i)
Line 4,529 ⟶ 4,877:
a imaginary => 1
a negated => (-1-1i)
a sqrt => (1.09868411346781+0.455089860562227i)
a2+b2 => ((7/6)+3i)
a2-b2 => ((-1/6)-1i)
a2*b2 => ((-5/3)+(5/3)i)
a2/b2 => ((21/40)-(3/40)i)
a2 reciprocal => ((2/5)-(4/5)i)</pre>
=={{header|smart BASIC}}==
Line 4,540 ⟶ 4,888:
<b>Original author unknown {:o(</b>
<
A=1+2i
B=3-5i
Line 4,556 ⟶ 4,904:
' gives output
-1+2i -1-2i</
=={{header|SNOBOL4}}==
Line 4,564 ⟶ 4,912:
{{works with|CSnobol}}
<
data('complex(r,i)')
Line 4,603 ⟶ 4,951:
output = printx( negx(a) ) ', ' printx( negx(b) )
output = printx( invx(a) ) ', ' printx( invx(b) )
end</
{{out}}
Line 4,612 ⟶ 4,960:
=={{header|Standard ML}}==
<syntaxhighlight lang="standard ml">
(* Signature for complex numbers *)
signature COMPLEX = sig
Line 4,656 ⟶ 5,004:
Complex.print_number(Complex.times i1 i2); (* -5 + 10i *)
Complex.print_number(Complex.invert i1); (* 1/5 - 2i/5 *)
</syntaxhighlight>
=={{header|Stata}}==
<
C(2,3)
2 + 3i
Line 4,701 ⟶ 5,049:
1.28247468 + .982793723i
end</
=={{header|Swift}}==
Line 4,708 ⟶ 5,056:
Use a struct to create a complex number type in Swift. Math Operations can be added using operator overloading
<
public struct Complex {
Line 4,755 ⟶ 5,103:
}
</syntaxhighlight>
Make the Complex Number struct printable and easier to debug by adding making it conform to CustomStringConvertible
<
extension Complex : CustomStringConvertible {
Line 4,786 ⟶ 5,134:
}
</syntaxhighlight>
Explicitly support subtraction and division
<
public func - (left:Complex, right:Complex) -> Complex {
return left + -right
Line 4,801 ⟶ 5,149:
return Complex(real: num.real/den.real, imaginary: num.imaginary/den.real)
}
</syntaxhighlight>
=={{header|Tcl}}==
{{tcllib|math::complexnumbers}}
<
namespace import math::complexnumbers::*
Line 4,813 ⟶ 5,161:
puts [tostring [* $a $b]] ;# ==> 1.94159+4.34159i
puts [tostring [pow $a [complex -1 0]]] ;# ==> 0.5-0.4999999999999999i
puts [tostring [- $a]] ;# ==> -1.0-i</
=={{header|TI-83 BASIC}}==
Line 4,848 ⟶ 5,196:
Note that the parentheses around ∠ notation are required. It has a related use in vectors: (1∠π/4) is a complex number, [1,∠π/4] is a vector in two dimensions in polar notation, and [(1∠π/4)] is a complex number in a vector.
=={{header|Unicon}}==
Takes advantage of Unicon's operator overloading extension and Unicon's Complex class. Negation is not supported by the Complex class.
<syntaxhighlight lang="unicon">import math
procedure main()
write("c1: ",(c1 := Complex(1.5,3)).toString())
write("c2: ",(c2 := Complex(1.5,1.5)).toString())
write("+: ",(c1+c2).toString())
write("-: ",(c1-c2).toString())
write("*: ",(c1*c2).toString())
write("/: ",(c1/c2).toString())
write("additive inverse: ",c1.addInverse().toString())
write("multiplicative inverse: ",c1.multInverse().toString())
write("conjugate of (4,-3i): ",Complex(4,-3).conjugate().toString())
end</syntaxhighlight>
{{out}}
<pre>c1: (1.5,3i)
c2: (1.5,1.5i)
+: (3.0,4.5i)
-: (0.0,1.5i)
*: (-2.25,6.75i)
/: (1.5,0.5i)
additive inverse: (-1.5,-3i)
multiplicative inverse: (0.1333333333333333,-0.2666666666666667i)
conjugate of (4,-3i): (4,3i)</pre>
=={{header|UNIX Shell}}==
{{works with|ksh93}}
<
float real=0
float imag=0
Line 4,925 ⟶ 5,301:
Complex_t d=(real=2 imag=1)
d.inverse
d.to_s # 0.4 + -0.2 i</
=={{header|Ursala}}==
Line 4,935 ⟶ 5,311:
c..add or ..csin). Real operands are promoted to complex.
<
v = 9.545e-01-3.305e+00j
Line 4,946 ⟶ 5,322:
complex..mul (u,v),
complex..sub (0.,u),
complex..div (1.,v)></
{{out}}
<pre><
Line 4,956 ⟶ 5,332:
=={{header|VBA}}==
<syntaxhighlight lang="vba">
Public Type Complex
re As Double
Line 5,045 ⟶ 5,421:
Debug.Print "Sqrt(a) = " & CPrint(c)
End Sub
</syntaxhighlight>
{{out}}
<pre>
Line 5,059 ⟶ 5,435:
Abs(a) = 3.35410196624968
Sqrt(a) = 1.55789954205168+0.962834868045836i
</pre>
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import math.complex
fn main() {
a := complex.complex(1, 1)
b := complex.complex(3.14159, 1.25)
println("a: $a")
println("b: $b")
println("a + b: ${a+b}")
println("a * b: ${a*b}")
println("-a: ${a.addinv()}")
println("1 / a: ${complex.complex(1,0)/a}")
println("a̅: ${a.conjugate()}")
}</syntaxhighlight>
{{out}}
<pre>a: 1.000000+1.000000i
b: 3.141590+1.250000i
a + b: 4.141590+2.250000i
a * b: 1.891590+4.391590i
-a: -1.000000-1.000000i
1 / a: 0.500000-0.500000i
a̅: 1.000000-1.000000i
</pre>
=={{header|Wortel}}==
{{trans|CoffeeScript}}
<
&[r i] @: {
^r || r 0
Line 5,092 ⟶ 5,491:
"1 / ({b}) = {b.inv.}"
"({!a.mul b}) / ({b}) = {`!.mul b.inv. !a.mul b}"
]</
{{out}}
<pre>(5 + 3i) + (4 - 3i) = 9
Line 5,103 ⟶ 5,502:
=={{header|Wren}}==
{{libheader|Wren-complex}}
<
var x = Complex.new(1, 3)
Line 5,115 ⟶ 5,514:
System.print("-x = %(-x)")
System.print("1 / x = %(x.inverse)")
System.print("x* = %(x.conj)")</
{{out}}
Line 5,131 ⟶ 5,530:
=={{header|XPL0}}==
<
func real CAdd(A, B, C); \Return complex sum of two complex numbers
Line 5,187 ⟶ 5,586:
COut(0, CInv(U,W)); CrLf(0);
COut(0, Conj(U,W)); CrLf(0);
]</
{{out}}
Line 5,199 ⟶ 5,598:
=={{header|Yabasic}}==
<
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
Line 5,246 ⟶ 5,645:
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
end if</
=={{header|zkl}}==
<
(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)
Line 5,256 ⟶ 5,655:
(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).conjugate().println(); // (3.00-4.00i)</
{{out}}
<pre>
Line 5,269 ⟶ 5,668:
=={{header|zonnon}}==
<
module Numbers;
type
Line 5,364 ⟶ 5,763:
Writeln(~b);
end Main.
</syntaxhighlight>
{{Out}}
<pre>
Line 5,377 ⟶ 5,776:
=={{header|ZX Spectrum Basic}}==
{{trans|BBC BASIC}}
<
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
Line 5,400 ⟶ 5,799:
1000 IF o(i)>=0 THEN PRINT o(r);" + ";o(i);"i": RETURN
1010 PRINT o(r);" - ";-o(i);"i": RETURN
</syntaxhighlight>
{{out}}
<pre>Result of addition is:
|