Advertisement

linear system of equations

Started by August 27, 2003 05:36 AM
2 comments, last by eloso 21 years, 5 months ago
Hi all, i have the following function to solve a linear system of equations for a 3x3 matrix:

Vector2d Matrix3x3::solve2d()
{
	Vector2d v;

	if (mComponents[1] != 0)
	{
		v.mY = (mComponents[6] - mComponents[7] * mComponents[0] / mComponents[1])
				/ (mComponents[3] - mComponents[4] * mComponents[0] / mComponents[1]);
		
		v.mX = (mComponents[7] - v.mY * mComponents[4]) / mComponents[1];
	}
	else if (mComponents[2] != 0)
	{
		v.mY = (mComponents[6] - mComponents[8] * mComponents[0] / mComponents[2])
				/ (mComponents[3] - mComponents[5] * mComponents[0] / mComponents[2]);
		
		v.mX = (mComponents[8] - v.mY * mComponents[5]) / mComponents[2];
	}
	else
	{
		v.mY = (mComponents[7] - mComponents[6] * mComponents[1] / mComponents[0])
				/ (mComponents[4] - mComponents[3] * mComponents[1] / mComponents[0]);
		v.mX = (mComponents[6] - v.mY * mComponents[3]) / mComponents[0];
	}

	return v;
}
In most cases this works fine, but for some values eg.

137.66466268987     0.0046204004420716   137.66466268987
-56.938009696394    -0.0019109944413589  -56.938009696394
0.0050000000000000  -148.97481767635     0.00000000000000
 
i get an -1.#IND for y instead of the correct value -3.35e-5. This is because my code steps into the first branch instead of the second which would produce the correct result. I know that this is a matter of precision so i have to determine which branch would produce the least error rate. Does anybody know a "smart" way for this? eloso
Read up on Gaussian elimination with partitial pivoting. Its probably the simplest algorithm that does what you are looking for.
Advertisement
Seems that your matrix is not inversible. A NxN system cannot be solved if one of the equation is a linear combination of the other equations (in your case Eq1 = -2.417799 x Eq2). If you want to detect such system, compute the determinant of the NxN matrix - if it''s zero then your system cannot be solved.

For 3x3 matrices I would recommand direct computation of the inverse matrix rather than gaussian elimination. Or direct solving of the equation system. And I would also recommand to check a math book for more informations about what are matrices (hey, they are not "da kwel way ya must go to code a l33t 3d engine

--
Emmanuel

well, i know my system can be solved

What exactly do you mean by direct solving the system? I know, the third row of the matrix isn''t needed. As you can see in my source i use only 2 rows. I see i could improve this function if one of the components is 0 but since this function is used in precompution only, speed doesn''t really matter.

To AP1:
Yes, the partial pivoting did it. Now i always get correct results.

big thanks

eloso

This topic is closed to new replies.

Advertisement