Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

Python complex numbers from C++ strange output

I'm working on translating some code from C++ to Python and some values in python output are wrong. The expected output is pairs of numbers stored in the array. In the python, I get a lot of 1-0j pairs first and then good ones. In C++ the greatest value is around 1.3 and in Python over 9. How do I have to modify my python code to get the output from C++.

main func C++, I know that S do nothing but I'll use it later:

int X = 1000;
int N = X;

complex<double> S;

for (int n=0; n<X; n++)
{
    S = complex<double>(0,0);
    for (int x=0; x<X; x++)
    {
        double r = cos(((2*M_PI)/X)*n*x);
        double i = sin(((2*M_PI)/X)*n*x);
        complex<double> t (r, -i);
        cout << t << endl;
    }
}

Python:

import numpy as np
from math import pi
import sys
 
np.set_printoptions(threshold=sys.maxsize)

X = 1000
N = X
S = np.zeros(0, dtype = complex)
T = np.zeros(0, dtype = complex)

n = 0
x = 0
for n in range(0, 1000, 1):
     # S = np.append(S, np.complex(0 ,0)
  
    for x in range(0, 1000, 1):
        r = np.cos(((2*pi)/X)*n*x)
        i  = np.sin(((2*pi)/X)*n*x)
        T = np.append(T, np.complex(r, -i))
        print(T)
        print('
')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's not clear why you think your Python code is equivalent to your C++ code. T = np.append(T, np.complex(r, -i)) is not equivalent to complex<double> t (r, -i);. The actual equivalent Python code to your C++, which produces the same output, is:

from numpy import cos, sin, pi # could also import from math instead of numpy, might affect speed though
X = 1000

for n in range(X):
    for x in range(X):
        r = cos(((2*pi)/X)*n*x)
        i = sin(((2*pi)/X)*n*x)
        t = complex(r, -i)
        print(t)

The way I tested this was by setting X to 5 in both sets of code and comparing the output. They were the same (with Python just showing more digits of precision).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...