Welcome to ARC Forums

Join our group of tech enthusiasts and Android developers

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

Discussion in 'Programming' started by ABHIJITH N RAJ, Jun 28, 2017.

  1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  1. ABHIJITH N RAJ

    ABHIJITH N RAJ HummingBird
    Staff Member

    4
    2
    310
    Ratings:
    +2 / 0 / -0
    #1 ABHIJITH N RAJ, Jun 28, 2017
    Last edited: Jun 28, 2017
    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
     
    • Funny Funny x 1

Share This Page