Numpy not solving matrix equation correctly

Viewed 190

In the code below, Is result not supposed to be the same as eqtn_ans[1] since numpy had no problem solving the simultaneous equation? Or I'm I missing something?

Since numpy was able to get the inverse of eqtn_coeffs doesn't that make the equation solvable?

import numpy as np

def solve_simultaneous_equation(eq_coef, ans):
        A = np.array(eq_coef)
        B = np.array(ans)
        E = np.linalg.solve(A,B)
        return E

eqtn_coeffs = [[0.13230431079864502, -0.4504314661026001, 0.6201357841491699], 
               [-0.04826474189758301, -0.4006437063217163, 1.5354962348937988], 
               [-0.22883379459381104, -0.3508559465408325, 2.4508566856384277]]

eqtn_ans = [0.0, 0.7853981852531433, 1.3258177042007446]

params = solve_simultaneous_equation(eqtn_coeffs, eqtn_ans)

result = np.dot(eqtn_coeffs[1],params)

print(result) # The result of this should be the same as eqtn_ans[1] 
              # but its not even though numpy was able to solve the equation.

result:

0.625
2 Answers

It is easy to see why you have a problem

np.linalg.det(eqtn_coeffs)

prints

3.3194268620340867e-17

If the determinant of a matrix is zero, then the linear system of equations it represents has no solution (to be mor precise, no desired unique solution). In other words, the system of equations contains at least two equations that are not linearly independent.

It looks like you've hit the quantization limit of an IEEE-754 double. params comes out to

[3.27075180e+15, 1.72019082e+15, 5.51642915e+14]

Each value of eqtn_coeffs is ~1. The differences between them are approximately zero. In fact, you see a number that is ~ULP multiplied by 1e-15.

The rest of eqtn_coeffs.dot(params) shows the same pattern. Notice the approximately correct proportions rounded to very small multiples of the nearest powers of two:

[0.125 0.75  1.25 ]

A simpler way to describe this is to say that your equations are poorly conditioned. They are not technically dependent in a mathematical sense, but may as well be to the precision available on your machine, hence the obscenely large parameters.

Related