So I need a lot of different table files and decided to try and create them with C. The code does in general what it's supposed to but I get -nan and -inf in the 2. and 3. cloumns (4-7 work fine).
4.0000000000e-02 -nan -inf
4.2000000000e-02 -nan -inf
4.4000000000e-02 -nan -inf
The values in these columns come from functions with input variables, so I probably made a mistake defining them. Since this is the first thing I ever did in C I'm sure I made a very dumb mistake so thanks in advance.
Here is the code
#include <stdio.h>
#include <math.h>
main()
{
FILE *fout;
double e,o,k,c,r;
printf("Define the relative dielectric constant:\n");
scanf("%d",&e);
printf("Define the cutoff radius:\n");
scanf("%d",&o);
k = (78-e)/(pow(o,3)*(156+e));
c = (1/o)+k*pow(o,2);
fout = fopen("table_XX_XX.xvg", "w");
fprintf(fout, "#\n# Tabulated Potential for AA-AA Interactions\n#\n");
for (r=0; r<=3; r+=0.002) {
double f = ((1/r)+k*pow(r,2)-c)/e;
double fprime = (pow(r,-2)-2*k*r)/e;
double g = -1/(pow(r,6));
double gprime = -6/(pow(r,7));
double h = 1/(pow(r,12));
double hprime = 12/(pow(r,13));
/* print output */
if (r<0.04) {
fprintf(fout, "%12.10e %12.10e %12.10e %12.10e %12.10e %12.10e %12.10e\n", r,0.0,0.0,0.0,0.0,0.0,0.0);
} else {
fprintf(fout, "%12.10e %12.10e %12.10e %12.10e %12.10e %12.10e %12.10e\n", r,f,fprime,g,gprime,h,hprime);
}
}
fclose(fout);
return(0);
}
As cited here, and here, `+/-inf, or nan are generated by such operations as:
1/0 = ∞
log (0) = -∞
sqrt (-1) = NaN
When using ratios, and or exponential operations, checks should always be included in your code to exclude exceptional values from being processed by such operations.
Walk through the sections of your code where
inf
ornan
values are being generated, identify how the ratios or functions might be assigned incorrect values, and address them. (eg. by surrounding that section of code with a test for illegal value, and set a condition to bypass the operation when such a value is present.)Keep in mind the difference between accepting and using the values of
+/-∞
andNaN
.When using them, the basic operations and math functions all accept
∞
andNaN
and produce sensible output. However, ∞ propagates through calculations as one would expect: for example,2 + ∞
=∞;
,4/∞;
=0
,atan (∞)
=pi;/2
.NaN
, on the other hand, infects any calculation that involves it. Unless the calculation would produce the same result no matter what real value replacedNaN
, the result isNaN
. (adapted from 2nd link above).