Thursday, July 9, 2009

Converting C code to Fortran?

Is there a site that can help me translate C code to Fortran or MATLAB??????

Converting C code to Fortran?
C to Fortran Converter: http://home.earthlink.net/~dave_gemini/c...





Note that some features may not be supported...
Reply:Here is an example of a C program and the equivalent version in Fortran-77. I used the Intel Fortan compiler for validation.





The program implements Simpson's rule to calculate the integral for the function





f(x) = 4/(1+x*x)





The value of this integral is pi





-- C version starts here ----------------------





#include %26lt;stdio.h%26gt;


#include %26lt;math.h%26gt;





double f(double x)


{


return 4.0/(1.0+x*x);


}





int _tmain(int argc, _TCHAR* argv[])


{


int i, n ;


double a=0.0, b=1.0, h, s1=0.0, s2=0.0, s3=0.0;





printf("Enter number of partitions (must be even) = ");


scanf("%d", %26amp;n) ;





h = (b-a)/(2.0*n) ;


s1 = (f(a)+ f(b));





for (i=1; i%26lt;2*n; i=i+2)


s2 = s2 + f(a + i*h);





for (i=2; i%26lt;2*n; i=i+2)


s3 = s3 + f(a + i*h);





printf("%20.12lf\n", (h/3.0)*(s1+ 4.0*s2 + 2.0*s3)) ;


return 0;





}





------ fortran version starts here --------





program fsimp





implicit none


integer i, n


double precision a, b, h, s1, s2, s3, f


a=0.0


b=1.0


s1=0.0


s2=0.0


s3=0.0





print *, 'Enter number of partitions (must be even) = '


read *, n





n = 10





h = (b-a)/(2.0*n)


s1 = (f(a)+ f(b))





i = 1


do while (i .lt. 2*n)


s2 = s2 + f(a + i*h)


i = i + 2


enddo





i = 2


do while (i .lt. 2*n)


s3 = s3 + f(a + i*h)


i = i + 2


enddo





print '(f20.12 )', (h/3.0)*(s1+ 4.0*s2 + 2.0*s3)








end program fsimp





function f(x)


double precision x, f


f = 4.0/(1.0+x*x)


end


No comments:

Post a Comment