Re: R: Re: Strange behaviour with numerical precision



Marco Zannoni <marco.zannoni@xxxxxxxxx> wrote:
I guess the operation real(Td,QP) creates a QP-variable which consists
of Td with a tail of junk concatenated to it.

It happens in the following compiled with gfortran-4.4.3

program test
implicit none
real(kind(1d0)) :: xDbl
real(kind(1e0)) :: xSngl
xDbl = 1.1d0
xSngl = real(xDbl,kind(xSngl))
write(*,*) xDbl
write(*,*) real(xSngl,kind(xDbl))
end program

I checked and it is exactly what happens!

In fact, in my example it happens because 1.1d0 is not represented
exactly. It does not happen with 0.5d0. To check with your number, I
tried the following (gfortran supports 18 decimal reals)

program test
implicit none
integer,parameter :: kind18 = selected_real_kind(18)
integer,parameter :: kind15 = selected_real_kind(15)
real(kind18) :: x18
real(kind15) :: x15
write(*,*) precision(x18),precision(x15)
x18 = 2.52459602520000000_kind18
x15 = real(x18,kind(x15))
write(*,*) x18
write(*,*) real(x15,kind(x18))
end program

and find output

18 15
2.5245960251999999999
2.5245960252000001489

Now the big questin: how do
I avoid this behaviour when convert from low precisi on to high
precision? Or, alternatively, how do I perform a high precision
difference between a low precision value and a high precision ones
without converting low to high?

I don't see the problem.
If the difference between the low-precision and the high-precision
number is smaller than the low-precision, the low-precision calculation
is OK. Only if the difference is larger than the low-precision you have
numerical instabilities. Eg.

low-precision calculation: 0.1234
high-precision calculation: 0.12345678
--> low-precision calculation is ok

low-precision calculation: 0.1244
high-precision calculation: 0.12345688
--> low-precision calculation is not ok
.