Fortran to C Code Conversion: Calculating Cosine of Angle Between Vectors
Fortran to C Code Conversion: Calculating Cosine of Angle Between Vectors
This example illustrates the process of converting a Fortran subroutine to its equivalent C function. The original Fortran code calculates the cosine of the angle between two 3D vectors.
Fortran Subroutine:
SUBROUTINE AnglecosVector(Cosangle,Vector1,Vector2)
IMPLICIT NONE
REAL(8) Cosangle,Vector1(3),Vector2(3),abdj,aa,bb
abdj=Vector1(1)*Vector2(1)+Vector1(2)*Vector2(2)+
+ Vector1(3)*Vector2(3)
aa=DSQRT(Vector1(1)*Vector1(1)+Vector1(2)*Vector1(2)+
+ Vector1(3)*Vector1(3))
bb=DSQRT(Vector2(1)*Vector2(1)+Vector2(2)*Vector2(2)+
+ Vector2(3)*Vector2(3))
Cosangle=abdj/(aa*bb+1.0D-50)
RETURN
END
Equivalent C Function:
void AnglecosVector(double *Cosangle, double Vector1[3], double Vector2[3]) {
double abdj, aa, bb;
abdj = Vector1[0]*Vector2[0] + Vector1[1]*Vector2[1] + Vector1[2]*Vector2[2];
aa = sqrt(Vector1[0]*Vector1[0] + Vector1[1]*Vector1[1] + Vector1[2]*Vector1[2]);
bb = sqrt(Vector2[0]*Vector2[0] + Vector2[1]*Vector2[1] + Vector2[2]*Vector2[2]);
*Cosangle = abdj / (aa*bb + 1.0e-50);
}
Explanation:
- Function Signature: The
SUBROUTINEin Fortran becomes thevoidfunction in C, accepting a pointer to the outputCosangle, and arrays for input vectorsVector1andVector2. - Data Types:
REAL(8)in Fortran translates todoublein C for floating-point numbers. - Array Indexing: Fortran uses 1-based indexing while C uses 0-based indexing. We adjust the array indices accordingly.
- Dot Product and Magnitudes: The core calculation is the same: dot product of vectors (
abdj) divided by the product of their magnitudes (aaandbb). - Small Constant Addition: The
1.0D-50in Fortran (representing1.0e-50in C) is a small value added to avoid division by zero when the magnitudes are close to zero.
This example demonstrates a basic conversion process, highlighting key differences between Fortran and C. For more complex code conversions, consider using tools like automatic translators or studying language-specific idioms and conventions.
原文地址: https://www.cveoy.top/t/topic/nZCs 著作权归作者所有。请勿转载和采集!