0

UPDATE:

I went around the problem with a DataFrame:

import pandas as pd
import numpy as np

dict = {'x0':[1,1,1,1,1],'x1':[2,3,5,7,8],'x2':[1,5,3,6,7], 'y':[3,2,4,5,8]}

df = pd.DataFrame(dict)



# y = β(0) + β1x1 + β2x2 

X = df[['x0','x1','x2']].to_numpy()

Y = df[['y']].to_numpy()

X_transpose = (X.transpose())

beta_hats  = np.linalg.inv(X_transpose.dot(X)).dot(X_transpose.dot(Y))

print(beta_hats)

df = pd.DataFrame(beta_hats)

df.rename(columns = {0:'Beta_Hats'}, inplace = True)

print(df)

I wrote the following program to find the beta coefficients from a set of matrices via NumPy. When I converted the array to a list, I ran into problems: some of the decimal points were off :

Array output: 
[[ 0.5 ]
 [ 1.  ]
 [-0.25]]

list output: [[0.49999999999999784], [1.0000000000000022], [-0.2500000000000009]]

I am aware Python has some limitations with calculations, but I was wondering if anyone has figured a way around this. Any help would be much appreciated! I haven't been coding for too long (since May) so sorry if this may seem a bit simple to some of you:

import pandas as pd
import numpy as np

dict = {'x0':[1,1,1,1,1],'x1':[2,3,5,7,8],'x2':[1,5,3,6,7], 'y':[3,2,4,5,8]}

df = pd.DataFrame(dict)



X = df[['x0','x1','x2']].to_numpy()

Y = df[['y']].to_numpy()


X_transpose = (X.transpose())

beta_hats  = np.linalg.inv(X_transpose.dot(X)).dot(X_transpose.dot(Y))

print(beta_hats)

list = beta_hats.tolist()

print(list)
Pedro
  • 1
  • 1
  • 2
    `tolist` is the right way. Your issue isn't with precision, but with how arrays and lists are displayed. `inv` is not numerically exact. – hpaulj Jul 08 '22 at 22:13
  • Please read: [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Jérôme Richard Jul 09 '22 at 14:12

0 Answers0