Next: Exercises Up: Programming in Maple Previous: File Input/Output of

Fortran and C output

The fortran and C commands generate output of Maple formulae in a format suitable for a Fortran or C compiler. This is useful when you have developed a formula in Maple, or perhaps a vector or matrix of formulae, and you wish to evaluate these formulae in a Fortran or C subroutine. How do you translate the Maple formulae into Fortran or C? The Maple functions fortran and C are written for this purpose. Here is an example. Suppose we have created the following polynomial in Maple which, by the way, is an approximation to the complementary error function on the range [2,4] accurate to 5 decimal digits.


 f :=  - 3.902704411 x + 1.890740683 - 1.714727839 x  + 3.465590348 x

                        7                4                 5                  6
      - .0003861021174 x  + .5101467996 x  - .09119265524 x  + .009063185478 x

It is not important to know what the complementary error function is for the purpose of this example though. It is in fact related to the Normal distribution in statistics. Neither is it important here to know how we created the approximation . We needed a rough approximation to this function in the given range because our Fortran and C libraries did not have this function built in. For the interested reader, we used the command chebyshev(erfc(x),x=2..4,10^(-5) to create a Chebyshev series approximation and used our `expand/T` routine that we wrote earlier to convert it to a polynomial. To evaluate the approximation above efficiently, we want to write the polynomial in Horner form. Then we want to generate Fortran code. We could do


> h := convert(f,horner);

h := 1.890740683 + ( - 3.902704411 + (3.465590348 + ( - 1.714727839

 + (.5101467996 + ( - .09119265524 + (.009063185478 - .0003861021174 x) x) x) x

) x) x) x

> fortran(h);
      t0 = 0.1890741E1+(-0.3902704E1+(0.346559E1+(-0.1714728E1+(0.510146
     #8E0+(-0.9119266E-1+(0.9063185E-2-0.3861021E-3*x)*x)*x)*x)*x)*x)*x

Maple has generated two lines of Fortran code complete with continuation character since the formula is longer than one line. The floating point numbers have automatically been translated to single precision Fortran E notation and have been truncated to 7 decimal digits. And Maple has put the result in the variable t0 for us. Let us now output C code into a file temp.c assigned to the variable . Note, the C function must first be loaded into Maple.


> readlib(C):
> C([r = h],filename=`temp.c`);

If we look at the file `temp.c` we find that it contains


      r = 0.1890740683E1+(-0.3902704411E1+(0.3465590348E1+(-0.1714727839E1+(
0.5101467996+(-0.9119265524E-1+(0.9063185478E-2-0.3861021174E-3*x)*x)*x)*x)*x)*
x)*x;

The reader can study the help pages for ?fortran and ?C for additional information capabilities and options to these commands.


bondaren@thsun1.jinr.ru