[Solved]Two functions may give the same result or Does it??? Think before you Type!!!

ABHIJITH N RAJ

Bronze I
Staff member
The very first time I was taken aback when I typed in the following code I was surprised I got the following results in python inorder to solve the linear equation ax=b

#The code to solve a linear equation in python
import numpy as np

a=np.array([[1,1],[1.5,4])
b=np.array([2200,5050])

#Using the solve function in numpy
x=np.solve(a,b)

#Using the inverse of a
v=np.linalg.inv(a).dot(b)

#Now when you check both x and v values are same but when you perform x==v you will get an entirely different value

In : v
Out: array([ 1500., 700.])
In : x
Out: array([ 1500., 700.])

x==v
#The result is
array([ True, False], dtype=bool)
which is not expected as both values shown were same

what happened may be realised if you check the element values individually

In : x
Out: 700.0

In : v
Out: 699.99999999999977

i.e, the value of v was actually only 699.99999999999977 no 700 and hence not equal. The correct answer corresponding to our linear equation is x and not v.

This is why built in functions are preferred most of the times over our own algorithms as appearances can be deceptive

Last edited: