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

  • This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

ABHIJITH N RAJ

Bronze III
Staff member
Developer
Mar 6, 2017
5
3
310
19
#1
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 [24]: v
Out[24]: array([ 1500., 700.])
In [25]: x
Out[25]: 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 [31]: x[1]
Out[31]: 700.0

In [32]: v[1]
Out[32]: 699.99999999999977

i.e, the value of v[1] 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: