GSL 的簡介
The library provides a wide range of mathematical routines such as random number generators, special functions and least-squares fitting. There are over 1000 functions in total with an extensive test suite.
專案位置在http://www.gnu.org/software/gsl/
第一個範例:
#include <stdio.h>
#include <gsl/gsl_sf_bessel.h>
int
main (void)
{
double x = 5.0;
double y = gsl_sf_bessel_J0 (x);
printf ("J0(%g) = %.18e\n", x, y);
return 0;
}
編譯後執行可得到,
$ ./tutor01
J0(5) = -1.775967713143382920e-01
再試一個例子
#include <stdio.h>
#include <gsl/gsl_blas.h>
int
main (void)
{
double a[] = { 0.11, 0.12, 0.13,
0.21, 0.22, 0.23 };
double b[] = { 1011, 1012,
1021, 1022,
1031, 1032 };
double c[] = { 0.00, 0.00,
0.00, 0.00 };
gsl_matrix_view A = gsl_matrix_view_array(a, 2, 3);
gsl_matrix_view B = gsl_matrix_view_array(b, 3, 2);
gsl_matrix_view C = gsl_matrix_view_array(c, 2, 2);
/* Compute C = A B */
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans,
1.0, &A.matrix, &B.matrix,
0.0, &C.matrix);
printf ("[ %g, %g\n", c[0], c[1]);
printf (" %g, %g ]\n", c[2], c[3]);
return 0;
}
編譯執行後,
$ ./tutor02
[ 367.76, 368.12
674.06, 674.72 ]
再來一例,求解x^5=1 的根
#include <stdio.h>
#include <gsl/gsl_poly.h>
int
main (void)
{
int i;
/* coefficients of P(x) = -1 + x^5 */
double a[6] = { -1, 0, 0, 0, 0, 1 };
double z[10];
gsl_poly_complex_workspace * w
= gsl_poly_complex_workspace_alloc (6);
gsl_poly_complex_solve (a, 6, w, z);
gsl_poly_complex_workspace_free (w);
for (i = 0; i < 5; i++)
{
printf ("z%d = %+.18f %+.18f\n",
i, z[2*i], z[2*i+1]);
}
return 0;
}
編譯執行後可得
$ ./tutor03
z0 = -0.809016994374947229 +0.587785252292473137
z1 = -0.809016994374947229 -0.587785252292473137
z2 = +0.309016994374947562 +0.951056516295153531
z3 = +0.309016994374947562 -0.951056516295153531
z4 = +1.000000000000000222 +0.000000000000000000
完全是用之前提到的makefile 來編譯:
CFLAGS = -g -Wall -std=gnu99 -O3
#LDLIBS= `pkg-config --libs gsl`
LDLIBS=-lgsl -lgslcblas -lm
OBJECTS=
CC=gcc
$(P): $(OBJECTS)
#include <stdio.h>
#include <gsl/gsl_multiset.h>
int
main (void)
{
gsl_multiset * c;
size_t i;
printf ("All multisets of {0,1,2,3} by size:\n") ;
for (i = 0; i <= 4; i++)
{
c = gsl_multiset_calloc (4, i);
do
{
printf ("{");
gsl_multiset_fprintf (stdout, c, " %u");
printf (" }\n");
}
while (gsl_multiset_next (c) == GSL_SUCCESS);
gsl_multiset_free (c);
}
return 0;
}
編譯執行後
$ ./tutor04
All multisets of {0,1,2,3} by size:
{ }
{ 0 }
{ 1 }
{ 2 }
{ 3 }
{ 0 0 }
{ 0 1 }
{ 0 2 }
{ 0 3 }
{ 1 1 }
...................................................
本書是作者做科學計算時的一些C語言的實戰心得,
而常用的函式庫就是GSL