How to calculate complex simultaneous equations in python? - python

I need to obtain three complex numbers from a set of three equations which is part of an error correction procedure for a set of S-parameters.
import numpy as np
G_A1 = -1 + 0j
G_A2 = 0 + 0j
G_A3 = 1 + 0j
G_M1 = -0.5323 - 0.0163j
G_M2 = -11.1951 - 37.7373j
G_M3 = 0.5528 + 0.1621j
a = np.array([[G_A1,G_A2,G_A3], [1,1,1], [(-G_A1*G_M1),(-G_A2*G_M2),(-G_A3,G_M3)]])
b = np.array([G_M1,G_M2,G_M3])
x = np.linalg.solve(a, b)
print(x)
This gives me the error
a = np.array([[G_A1,G_A2,G_A3], [1,1,1], [(-G_A1*G_M1),(-G_A2*G_M2),(-G_A3,G_M3)]])
TypeError: a float is required
I thought I might as well try to convert the complex values to float but then I get this error.
G_M1 = float(-0.5323 - 0.0163j)
TypeError: can't convert complex to float
If complex values cannot be converted to float, what alternative method should I be using here?

You have a typo in the last entry of last row which makes it a tuple
(-G_A3,G_M3)
and leads to a TypeError as an element. If you correct that the problem goes away. You also don't need to put parentheses around the expressions in this case anyways.

Related

Numerically append binary numbers in np.array

Considering the following example array :
a = np.array([0,1,1,0,1,1,1,0,1,0])
Which could be of any dtype (int, float...)
How would I get the following output without using nasty loops and string casts ?
np.array([0b01,0b10,0b11,0b10,0b10])
a = a.astype(int)
output = a[0::2] * 2 + a[1::2]
Gives the array you've described (though it doesn't print in binary).

Convert a scipy interp1d array to a float value in Python

in my current project I have currently a conversion issue:
In a first step I am interpolating two lists with scipy interp1d.
f_speed = scipy.interpolate.interp1d(t, v, 'cubic')
After that I want to get one specific point in this function. This value is now an array from scipy with only one value in it.
currentSpeed = f_speed(tpoint)
# result: array(15.1944)
As a last step I want to calculate other values with the value from the interpolated function, but I only get 0 as a value. There is no Error at all.
real_distance = currentSpeed * (1/15) # some calculations
# result: 0, all results with further calculations are zero
I need a conversion from scipy array to a regular float value to proceed my calculations. Is there any function to do this?
I tried several things like V = currentSpeed[0], or .tolist from numpy (not possible in scipy)...
Thanks for your help in advance!!
You did not specify which Python version you're using, but if you're using Python 2.7, then operator / stands for integer division. It means that 1/15 will produce 0. Multiplying something with this results will end up being 0, regardless of how you access array values.
To solve the problem, make sure at least one operand is a float number.
result1 = 1/15 # Produces 0
result2 = 1.0/15 # Produces 0.06666666666666667
If you apply this to your code, you should use
real_distance = currentSpeed * (1.0/15)
Are you using Python 2? If so the problem is the division.
Integer division will result in an integer so 1/15 will result in 0.
Try 1.0/15 instead. By using 1.0 you make it explicitly a float an then the result will be as expected.

Subtracting two numbers of any base between 2 and 10

For two numbers x and y that are base b, does this work for subtracting them? The numbers are given in string format and 2 <= b <= 10.
def n2b(n, b): # function to convert number n from base 10 to base b
if n == 0:
return 0
d = []
while n:
d.append(int(n % b))
n /= b
return ''.join(map(str,d[::-1]))
x = int(x,b) # convert to integers in base 10
y = int(y,b)
z = x - y
z = n2b(z,b) # convert back to base b, still in integer form
You have some confusion about how integers work in python. As the comments above say: python always stores integers in binary form and only converts them to a base when you print them. Depending on how you get x and y and how you need to give back z the code needs to be different
Situation 1: x, y and z are all integers
In this case you only need to do
z = x - y
And you're done.
Situation 2: x, y and z are all strings
In this case you first need to convert the strings into integers with the right base. I think that's your case, since you already deal with int(x, b) which is correct to transform a string into an integer (e.g. int("11", 2) gives 3 (integer represented in base 10). I would advice you to reform your code into something like this:
x_int = int(x, b)
y_int = int(y, b)
z_str = n2b(x_int - y_int, b)
In your code x is first a string and then an integer, which is bad practice. So e.g. use x_int instead of x.
Now it comes down to if your n2b function is correct. It looks good from the distance, although you're not handling signs and bases bigger than 10. There is a broadly accepted convert integer to base b answer so you might take this to be sure.
This is exactly the problem I just ran into in the google foobar challenge (which I suspect is the same source of ops problem). Granted its years later and op has no use for my answer but someone else might.
The issue
The function op used looked a lot like a copy and paste of this provided by the accepted answer but slightly modified (although I didn't look to closely).
I used the same function and quickly realized that I needed my output to be a string. Op appears to have realized the same thing based on the return statement at the end of the function.
This is why most of the test cases passed. Op did almost everything right.
See, the function begins with
if n==0:
return 0
One of the test cases in the foobar challenge uses 0 as the input. Its an easy line to miss but a very important one.
Solution
When I was presented this problem, I thought about the possible outlier cases. 0 was my first idea (which turned out to be right). I ran the program in vscode and would ya look at that - it failed.
This let me see the error message (in my case it was a list rather than int but op would have received a similar error).
The solution is simply changing return 0 to return '0' (a string rather than int)
I wasn't super excited to write out this answer since it feels a bit like cheating but its such a small detail that can be so infuriating to deal with. It doesn't solve the challenge that foobar gives you, just tells you how to get past a speed bump along the way.
Good luck infiltrating commander lambda's castle and hopefully this helps.

python: inputting a negative value into array keeps giving me 256 minus that value (image- prewitt edge detection)

I am trying to do simple prewitt edge detection on an image and output 2 images with horizontal and vertical edges. For some reason, whenever the output value should be negative (for example -3), my output array ends up with 256 minus that value (253) giving me a huge amount of background. I tried adding these if/elif/else statements but that helped not at all. I am using the code below and clueless as to what's going wrong:
for i in range(1,(len(os.listdir(images)))):
image=plt.imread(images+(os.listdir(images)[i]))
if len(image.shape)>2:
img=image[:,:,0]
else:
img=image
imgC=deepcopy(img)
imgD=deepcopy(img)
imgE=deepcopy(img)
for x in range(1,img.shape[1]-2):
for y in range(1,img.shape[0]-2):
avgA=(img[(y-1),x]+img[(y-1),(x+1)]+img[(y-1),(x-1)])
avgC=(img[(y+1),x]+img[(y+1),(x+1)]+img[(y+1),(x-1)])
avgT=(img[(y-1),(x-1)]+img[y,(x-1)]+img[(y+1),(x-1)])
avgB=(img[(y-1),(x+1)]+img[y,(x+1)]+img[(y+1),(x+1)])
if (avgA-avgC)<0:
imgC[y,x]=0
elif (avgA-avgC)>255:
imgC[y,x]=255
else:
imgC[y,x]=(avgA-avgC)
if (avgT-avgB)<0:
imgD[y,x]=0
elif (avgT-avgB)>255:
imgD[y,x]=255
else:
imgD[y,x]=(avgT-avgB)
imgE[y,x]=math.sqrt(((imgC[y,x]**2)+(imgD[y,x]**2)))
Values in that image are stored as unsigned bytes (0..255 range), so this is probably the problem as subtracting two unsigned bytes would lead to overflow and you would get that 253 instead of -3.
You need to convert those values into an int. Something like this could work:
...
avgA = int(img[(y-1),x]) + int(img[(y-1),(x+1)]) + int(img[(y-1),(x-1)])
avgC = int(img[(y+1),x]) + int(img[(y+1),(x+1)]) + int(img[(y+1),(x-1)])
avgT = int(img[(y-1),(x-1)]) + int(img[y,(x-1)]) + int(img[(y+1),(x-1)])
avgB = int(img[(y-1),(x+1)]) + int(img[y,(x+1)]) + int(img[(y+1),(x+1)])
imgC[y, x] = avgA - avgC
imgD[y, x] = avgT - avgB
...
But I'm pretty sure you would get better (faster, less error prone code) results using generic convolution
function, like PIL.Image.filter(''<filter>'') with filter matrix created using
PIL.ImageFilter.Kernel(..) for PIL library - http://pillow.readthedocs.org/en/latest/reference/ImageFilter.html
Or convolve of numpy/scipy libraries, as shown here: http://juanreyero.com/article/python/python-convolution.html
Edit: as Julien Spronck pointed out - your resulting value in imgE is completely out of range and you should generally divide it by a number of pixels (i.e. sum of all values in the convolution matrix) used in calculation of that result.

Why subtract a value from itself (x - x) in Python?

In NumPy functions, there are often initial lines that do checking of variable types, forcing them to be certain types, etc. Can someone explain the point of these lines in scipy.signal.square? What does subtracting a value from itself do?
t,w = asarray(t), asarray(duty)
w = asarray(w + (t-t))
t = asarray(t + (w-w))
source
I believe that this will make the final w and t have the same type. For example, if you start with float and int, you will end up with both being float arrays which is better for subsequent operations.

Categories

Resources