GSL sample: Solving 2nd and 3rd degree Algebraic Equations

Last Update: Oct. 4, 2007


Sample code

2and3rd_degree_eq.c

/***********************************************/
/* T.Kouya's GSL sample program collection     */
/*                 Solving Algebraic Equations */
/*                   Written by Tomonori Kouya */
/*                                             */
/* Version 0.01: 2007-10-01                    */
/***********************************************/
#include <stdio.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_poly.h>

int main(void)
{
	int i;
	double coef[128], sol[128];
	gsl_complex csol[128];

/* Solve Linear and Quadratic Equations */
	printf("Solve Quadratic Equations\n");

	/* (1) 3 * x - 2 = 0 */
	gsl_poly_solve_quadratic(0.0, 3.0, -2.0, &sol[0], NULL);
	printf("x = %g\n", sol[0]);

	/* (2) 2 * x^2 - 3 * x - 5 = 0 */
	gsl_poly_solve_quadratic(2.0, -3.0, -5.0, &sol[0], &sol[1]);
	printf("x1, x2 = %g, %g\n", sol[0], sol[1]);

	/* (3) 3 * x^2 - 5 * x + 9 = 0 */
	gsl_poly_complex_solve_quadratic(3.0, -5.0, 9.0, &csol[0], &csol[1]);
	printf("re(x1), im(x1) = %g, %g\n", GSL_REAL(csol[0]), GSL_IMAG(csol[0]));
	printf("re(x2), im(x2) = %g, %g\n", GSL_REAL(csol[1]), GSL_IMAG(csol[1]));

/* Solve Cubic Equation */
	printf("\nSolve Monic Cubic Equation\n");

	/* x^3 + 2 * x^2 + 3 * x + 4 = 0 */
	gsl_poly_complex_solve_cubic(2.0, 3.0, 4.0, &csol[0], &csol[1], &csol[2]);
	for(i = 0; i < 3; i++)
		printf("re(x%d), im(x%d) = %g, %g\n", i, i, GSL_REAL(csol[i]), GSL_IMAG(csol[i]));

	return 0;
}

Example execution

$ ./2and3rd_degree_eq
Solve Quadratic Equations
x = 0.666667
x1, x2 = -1, 2.5
re(x1), im(x1) = 0.833333, -1.51841
re(x2), im(x2) = 0.833333, 1.51841

Solve Monic Cubic Equation
re(x0), im(x0) = -1.65063, 0
re(x1), im(x1) = -0.174685, -1.54687
re(x2), im(x2) = -0.174685, 1.54687

<- Go back