Arithmetic/Complex: Difference between revisions

+Icon+Unicon
(+Icon+Unicon)
Line 880:
print,1/x
( 0.500000, -0.500000)</lang>
 
== Icon and Unicon ==
==={{header|Icon}}===
Icon doesn't provide native support for complex numbers. Support is included in the IPL.
<lang Icon>procedure main()
 
SetupComplex()
a := complex(1,2)
b := complex(3,4)
 
c := complex(&pi,1.5)
d := complex(1)
e := complex(,1)
 
every v := !"abcde" do write(v," := ",cpxstr(variable(v)))
 
write("a+b := ", cpxstr(cpxadd(a,b)))
write("a-b := ", cpxstr(cpxsub(a,b)))
write("a*b := ", cpxstr(cpxmul(a,b)))
write("a/b := ", cpxstr(cpxdiv(a,b)))
write("neg(a) := ", cpxstr(cpxneg(a)))
write("inv(a) := ", cpxstr(cpxinv(a)))
write("conj(a) := ", cpxstr(cpxconj(a)))
write("abs(a) := ", cpxabs(a))
write("neg(1) := ", cpxstr(cpxneg(1)))
end</lang>
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.
<lang Icon>
link complex # for complex number support
 
procedure SetupComplex() #: used to setup safe complex
COMPLEX() # replace complex record constructor
SetupComplex := 1 # never call here again
return
end
 
procedure COMPLEX(rpart,ipart) #: new safe record constructor and coercion
initial complex :=: COMPLEX # get in front of record constructor
return if /ipart & (type(rpart) == "complex")
then rpart # already complex
else COMPLEX( real(\rpart | 0.0), real(\ipart|0) ) # create a new complex number
end
 
procedure cpxneg(z) #: negate z
z := complex(z) # coerce
return complex( -z.rpart, -z.ipart)
end
 
procedure cpxinv(z) #: inverse of z
local denom
z := complex(z) # coerce
 
denom := z.rpart ^ 2 + z.ipart ^ 2
return complex(z.rpart / denom, z.ipart / denom)
end</lang>
To take full advantage of the overloaded 'complex' procedure, the other cpxxxx procedures would need to be rewritten or overloaded.
 
Sample output:
<pre>#complexdemo.exe
 
a := (1.0+2.0i)
b := (3.0+4.0i)
c := (3.141592653589793+1.5i)
d := (1.0+0.0i)
e := (0.0+1.0i)
a+b := (4.0+6.0i)
a-b := (-2.0-2.0i)
a*b := (-5.0+10.0i)
a/b := (0.44+0.08i)
neg(a) := (-1.0-2.0i)
inv(a) := (0.2+0.4i)
conj(a) := (1.0-2.0i)
abs(a) := 2.23606797749979
neg(1) := (-1.0+0.0i)</pre>
 
==={{header|Unicon}}===
This Icon solution works in Unicon.
 
This could be better implemented as an object. Unicon doesn't allow for operator overloading at the current time.
 
=={{header|J}}==
Anonymous user