简体   繁体   中英

How to find negative imaginary parts of values in an array then turning them to positive?

I have a function a=x*V where x assumes thousands of values as x = arange(1,1000,0.1) and V is a combination of other constants. These make a always complex (has nonzero real and imaginary parts). However, because a depends on other values, the imag(a) can be negative for some x 's.

For what I am doing, however, I need imag(a) to be always positive, so I need to take the negative values and turn them into positive.

I have tried doing

if imag(a)<0:
    imag(a) = -1*imag(a)

That didn't seem to work because it gives me the error: SyntaxError: Can't assign to function call . I thought it was because it's an array so I tried any() and all() , but that didn't work either.

I'm out of options now.

IIUC:

In [35]: a = np.array([1+1j, 2-2j, 3+3j, 4-4j])

In [36]: a.imag *= np.where(a.imag < 0, -1, 1)

In [37]: a
Out[37]: array([ 1.+1.j,  2.+2.j,  3.+3.j,  4.+4.j])

You can't redefine a function that way. It would be like saying

sqrt(x) = 2*sqrt(x)

What you can do is reassign the value of a (not imag(a) ).

if imag(a) < 0
    a = a - 2*imag(a)*j

For example, if a = 3 - 5j , then it would give you

3 - 5j - 2(-5)j = 3 + 5j

It appears to be faster than doing subtraction. For a full function:

import numpy as np

def imag_abs(x):
    mask = x.imag < 0
    x[mask] = np.conj(x[mask])
    return x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM