Equivalent of j in NumPy

In Python, 1j or 0+1j is a literal of complex type. You can broadcast that into an array using expressions, for example In [17]: 1j * np.arange(5) Out[17]: array([ 0.+0.j, 0.+1.j, 0.+2.j, 0.+3.j, 0.+4.j]) Create an array from literals: In [18]: np.array([1j]) Out[18]: array([ 0.+1.j]) Note that what Michael9 posted creates a complex, not a … Read more

Use scipy.integrate.quad to integrate complex numbers

What’s wrong with just separating it out into real and imaginary parts? scipy.integrate.quad requires the integrated function return floats (aka real numbers) for the algorithm it uses. import scipy from scipy.integrate import quad def complex_quadrature(func, a, b, **kwargs): def real_func(x): return scipy.real(func(x)) def imag_func(x): return scipy.imag(func(x)) real_integral = quad(real_func, a, b, **kwargs) imag_integral = quad(imag_func, … Read more

Why does C++ mandate that complex only be instantiated for float, double, or long double?

You can’t properly implement many of the std::complex operations on integers. E.g., template <class T> T abs(const complex<T> &z); for a complex<long> cannot have T = long return value when complex numbers are represented as (real,imag) pairs, since it returns the value of sqrt(pow(z.real(), 2) + pow(z.imag(), 2)). Only a few of the operations would … Read more

How to perform approximate structural pattern matching for floats and complex

The key to the solution is to build a wrapper that overrides the __eq__ method and replaces it with an approximate match: import cmath class Approximately(complex): def __new__(cls, x, /, **kwargs): result = complex.__new__(cls, x) result.kwargs = kwargs return result def __eq__(self, other): try: return isclose(self, other, **self.kwargs) except TypeError: return NotImplemented It creates approximate … Read more

Why is log(inf + inf j) equal to (inf + 0.785398 j), In C++/Python/NumPy?

The free final draft of the C99 specification says on page 491 clog(+āˆž, +iāˆž) returns +āˆž + iĻ€/4. This is still the case currently. The C++ specification explains the same rules with the note The semantics of this function are intended to be consistent with the C function clog. I agree the behaviour is confusing … Read more

Numpy: Creating a complex array from 2 real ones?

This seems to do what you want: numpy.apply_along_axis(lambda args: [complex(*args)], 3, Data) Here is another solution: # The ellipsis is equivalent here to “:,:,:”… numpy.vectorize(complex)(Data[…,0], Data[…,1]) And yet another simpler solution: Data[…,0] + 1j * Data[…,1] PS: If you want to save memory (no intermediate array): result = 1j*Data[…,1]; result += Data[…,0] devS’ solution below … Read more