PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 18, 2022

[FIXED] How to get the integer part of the solution of system of linear equation using numpy?

 August 18, 2022     numpy, output, python, python-3.x, type-conversion     No comments   

Issue

import numpy as np

# Linear Equations
# x+3y-2z=5
# 3x+5y+6z=7
# 2x+4y+3z=8

A = np.array([[1,3,-2], [3,5,6], [2,4,3]])
B = np.array([[5,7,8]])
B = B.T
ans = np.linalg.solve(A, B)
print(ans)

I wanted to solve these system of liner equation and print the values of x y and z using Gaussian Elimination The output is an array as expected.

OUTPUT:    
[  [-15.]     
 [  8.]       
 [  2.]  ]

I just want it as integer like -15, 8, 2 so I can then print out values x=-15, y=8, z=2 if I try converting it to int(ans[0])(or even to a list) but its giving their floor value that is -14, 7, 1 respectively. Please tell how can I get the value -15, 8, 2 as integers.

PS: I tried with string and got the desired value but it is tedious to do and it would be great to get integers directly for further operations.


Solution

The problem is that the result in ans are floats, the result is not actually [-15, 8, 2] even though that is what is displayed. Hence, when using ans[0][0] you will get something like: -14.999999999999993.

Now, since it's not a whole number, when using int() python will automatically round down. This is why you get -14 instead.

One possible solution would be to use np.rint which will round elements in an numpy array to the nearest integer. Below, the list is also flattened to 1-dimension:

ans = np.rint(ans).flatten()

Now, accessing the elements as ints can be done with ans[0], ans[1], etc.



Answered By - Shaido
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing