Home:ALL Converter>How to use two dimensional arrays, Inverses, and multiplication to get solutions to a given linear equation?

How to use two dimensional arrays, Inverses, and multiplication to get solutions to a given linear equation?

Ask Time:2015-03-08T10:13:43         Author:Raoul Duke

Json Formatter

Given these equations:

ax + by = c

dx + ey = f

#include<stdio.h>
#include<stdlib.h>


int main (void){
//Data
float extra;
float x[2];
float y[2];
float solution[2];
float coef[2][2];

printf("Give Numbers:\n");
scanf("%f %f %f %f %f %f"
,&coef[0][0],  &coef[0][1], &solution[0],
&coef[1][0],  &coef[1][1], &solution[1]);


// Create Determinant
float det;
det = (coef[0][0] * coef[1][1] - coef[0][1] * coef[1][0]);


//Setting the Inverse
extra = coef[0][0];
coef[0][0] =   coef[1][1] / det;
coef[1][1] = extra / det;
coef[1][0] = -coef[1][0] / det;
coef[0][1] =  -coef[0][1] / det;





//Multiplication
y[0] = (coef[1][1]*solution[0]-solution[1]*coef[0][1]) / det;
x[1] = (coef[0][0]*solution[1]-solution[0]*coef[1][0]) / det;

//Print statements
printf("'Y' = %f\n" , y[0]);
printf("'X' = %f\n" , x[1]);
printf("Det= %f\n",det);

}

I am writing a program to solve two simultaneous linear equations with two unknowns.

I have six single-precision floating-point numbers a, b, c, d, e, f each separated by whitespace. These numbers are meant to be interpreted as the pair of equations ax+by=c dx+ey=f To solve this, first put the coefficient into a two-by-two matrix: [ a b ] [ d e ] And put the constant values into an array: [ c f ] Then invert the coefficient matrix by finding its determinant: det = ( ae - bd ) If the determinant is 0, terminate at this point with the error message "too complicated"

The inverse of the coefficient matrix is then [ e/det -b/det ] [ -d/det a/det ] This should be multiplied by the constant array to yeild [ (ec-fb)/det (af-cd)/det ]

EXAMPLE:

ax+by=c dx+ey=f

CORRECT INPUT/OUTPUT

give numbers

1 2 3 4 5 6

x=-1.000000

y=2.000000

MY INPUT/OUTPUT

Give Numbers:

1 2 3 4 5 6

y = 1.6666667 x = 4.6666667

det = -3.0000

Author:Raoul Duke,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/28922354/how-to-use-two-dimensional-arrays-inverses-and-multiplication-to-get-solutions
Leandro Caniglia :

When your code reads the input {1 2 3 4 5} it represents the equations\n\n1 * x + 2 * y = 3\n4 * x + 5 * y = 6\n\n\nThe correct answer is indeed x = -1 , y = 2. Your program does not compute the correct answer because of the Multiplication part, which should read:\n\nx[0] = coef[0][0] * solution[0] + coef[0][1] * solution[1];\nx[1] = coef[1][0] * solution[0] + coef[1][1] * solution[1]\n\n\nThe reason being that once you have the inverse the only that remains is to multiply it by the solution vector.",
2015-03-08T02:46:18
yy