equal numpy array solve in python np.array([0,4,2])*x==np.array([0,8,4])?

Viewed 32

Given two arrays, A and B:

A=np.array([0,4,2])
B=np.array([0,8,4])

I want to know if I can multiply A by a scalar (x) and get B (A*x==B?) and if that is the case I want to know the value of the scalar (in this case 2). I have searched and tried the solve function without luck

1 Answers

If A*x = B, then x = B/A for A ≠ 0.

You can do this:

A=np.array([0,4,2])
B=np.array([0,8,4])

# remove indices where A is null
m = A!=0

# ensure B values are null where A value are null
assert np.allclose(B[~m], 0)

# compute B/A
out = B[m]/A[m]

# ensure all values are (almost) equal
assert np.allclose(out-out[0], 0)

# print result
print(out[0])

output: 2.0

Related