Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fortran - want to round to one decimal point

In fortran I have to round latitude and longitude to one digit after decimal point.

I am using gfortran compiler and the nint function but the following does not work:

print *, nint( 1.40 * 10. ) / 10.    ! prints 1.39999998
print *, nint( 1.49 * 10. ) / 10.    ! prints 1.50000000

Looking for both general and specific solutions here. For example:

  1. How can we display numbers rounded to one decimal place?

  2. How can we store such rounded numbers in fortran. It's not possible in a float variable, but are there other ways?

  3. How can we write such numbers to NetCDF?

  4. How can we write such numbers to a CSV or text file?

like image 702
gansub Avatar asked Dec 04 '22 00:12

gansub


2 Answers

As others have said, the issue is the use of floating point representation in the NetCDF file. Using nco utilities, you can change the latitude/longitude to short integers with scale_factor and add_offset. Like this:

ncap2 -s 'latitude=pack(latitude, 0.1, 0); longitude=pack(longitude, 0.1, 0);' old.nc new.nc
like image 169
Robert Davy Avatar answered Dec 28 '22 06:12

Robert Davy


There is no way to do what you are asking. The underlying problem is that the rounded values you desire are not necessarily able to be represented using floating point.

For example, if you had a value 10.58, this is represented exactly as 1.3225000 x 2^3 = 10.580000 in IEEE754 float32.

When you round this to value to one decimal point (however you choose to do so), the result would be 10.6, however 10.6 does not have an exact representation. The nearest representation is 1.3249999 x 2^3 = 10.599999 in float32. So no matter how you deal with the rounding, there is no way to store 10.6 exactly in a float32 value, and no way to write it as a floating point value into a netCDF file.

like image 33
2 revs Avatar answered Dec 28 '22 07:12

2 revs