Jump to content

Roots of unity: Difference between revisions

no edit summary
(Added Haskell example)
No edit summary
Line 78:
 
=={{header|C++}}==
<cpp>#include <complex>
#include <iostreamcmath>
#include <ostreamiostream>
 
double const pi = 4 * std::atan(1);
 
int main()
{
for (int n = 2; n <= 10; ++n)
{
std::cout << n << ": ";
for (int k = 0; k < n; ++k)
std::cout << std::polar(1, 2*pi*k/n) << " ";
std::cout << std::endl;
}
}</cpp>
}
 
=={{header|Forth}}==
Line 154:
=={{header|Java}}==
Java doesn't have a nice way of dealing with complex numbers, so the real and imaginary parts are calculated separately based on the angle and printed together. There are also checks in this implementation to get rid of extremely small values (< 1.0E-3 where scientific notation sets in for <tt>Double</tt>s). Instead, they are simply represented as 0. To remove those checks (for very high <tt>n</tt>'s), remove both if statements.
<java>public static void unity(int n){
//all the way around the circle at even intervals
for(double angle = 0;angle < 2 * Math.PI;angle += (2 * Math.PI) / n){
double real = Math.cos(angle); //real axis is the x axis
if(Math.abs(real) < 1.0E-3) real = 0.0; //get rid of annoying sci notation
double imag = Math.sin(angle); //imaginary axis is the y axis
if(Math.abs(imag) < 1.0E-3) imag = 0.0; //get rid of annoying sci notation
System.out.print(real + " + " + imag + "i\t"); //tab-separated answers
}
}</java>
}
 
=={{header|Perl}}==
{{works with|Perl|5.8.8}}
{{libheader|Math::Complex}}
<perl>use Math::Complex;
 
foreach $n (1 .. 10) {
printf "%2d ", $n;
foreach $k (1 .. $n) {
$ret = expcplxe($k1, *2 2*i pi * pi$k / $n);
$ret->display_format('style' => 'cartesian', 'format' => '%.3f');
print "($ret)";
}
print "\n";
}</perl>
}
 
Output:
Line 198:
 
Function <code>nthroots()</code> returns all n-th roots of unity.
<python>from cmath import exp, pi
def nthroots(n):
return [exp(k * 2j * pi / n) for k in range(1, n + 1)]</python>
Example:
>>> f = nthroots
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.