Roots of unity: Difference between revisions
Content added Content deleted
(added Fortran) |
|||
Line 256: | Line 256: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
{{works with|Python|2.5}} |
{{works with|Python|2.5}} |
||
<python> |
|||
import cmath |
|||
# format complex to 4 decimal places |
|||
Function <code>nthroots()</code> returns all n-th roots of unity. |
|||
class Complex(complex): |
|||
<python>from cmath import exp, pi |
|||
def |
def __repr__(self): |
||
re_fmt = "%7.4f" |
|||
return [exp(k * 2j * pi / n) for k in range(1, n + 1)]</python> |
|||
im_fmt = ("+" if self.imag > 0 else "-") + "%6.4fj" |
|||
Example: |
|||
return (re_fmt+im_fmt) % (self.real, abs(self.imag)) |
|||
>>> f = nthroots |
|||
for root in range(2, 10+1): |
|||
... print map(lambda c: ("%.3f " + ("+" if c.imag > 0 else "-") + " %.3gj") % (c.real, abs(c.imag)), f(n)) |
|||
print "%3d"%root, [Complex(cmath.exp(2j*cmath.pi*n/root)) for n in range(1, root/2+1)] |
|||
['1.000 - 2.45e-016j'] |
|||
</python> |
|||
['-1.000 + 1.22e-016j', '1.000 - 2.45e-016j'] |
|||
Output: |
|||
['-0.500 + 0.866j', '-0.500 - 0.866j', '1.000 - 2.45e-016j'] |
|||
2 [-1.0000+0.0000j] |
|||
3 [-0.5000+0.8660j] |
|||
4 [ 0.0000+1.0000j, -1.0000+0.0000j] |
|||
5 [ 0.3090+0.9511j, -0.8090+0.5878j] |
|||
6 [ 0.5000+0.8660j, -0.5000+0.8660j, -1.0000+0.0000j] |
|||
7 [ 0.6235+0.7818j, -0.2225+0.9749j, -0.9010+0.4339j] |
|||
8 [ 0.7071+0.7071j, 0.0000+1.0000j, -0.7071+0.7071j, -1.0000+0.0000j] |
|||
9 [ 0.7660+0.6428j, 0.1736+0.9848j, -0.5000+0.8660j, -0.9397+0.3420j] |
|||
10 [ 0.8090+0.5878j, 0.3090+0.9511j, -0.3090+0.9511j, -0.8090+0.5878j, -1.0000+0.0000j] |
|||
=={{header|Seed7}}== |
=={{header|Seed7}}== |