Silverfrost Forums

Welcome to our forums

Real representation

12 Nov 2011 9:10 #9215

I am using a routine to convert a character to real.

I have:

'7.500000000000000E-2' (character)

The routine which converts character to real can read only the first 20 characters.

Please advise how to represent only 20 characters in '7.500000000000000E-2' such that the correct real number is obtaned.

I do not have access to the routine which carries out the conversion - so please help howw to send the 20 characters such that the correct real number 7.5E-2 is obtain ed.

14 Nov 2011 5:19 #9217

You could provide your own routine to read, such as adapting from the following example: character real_string25, aa(3)25 real10 x real8 y integer4 iostat,i ! aa(1) = '7.500000000000000E-2' aa(2) = '3.500000000000003400E-2' aa(3) = '3.500003400000000000E-20' ! do i = 1,3 real_string = aa(i) read (real_string, fmt='(bn,f25.0)', iostat=iostat) x write (,) 'String = ',real_string write (,) 'X = ',x write (,) 'error = ',iostat y = x write (,) 'Y = ',y call trim_real_string (real_string) write (,*) 'String = ',real_string end do ! end

subroutine trim_real_string (real_string)
!
!  trims training 0 from real number string
!
 character real_string*(*)
!
 character real_part*25, exponent_part*10
 integer*4 ie,i
!
 ie = index(real_string, 'E')
!
 if (ie > 0) then
   real_part     = real_string(1:ie-1)
   exponent_part = real_string(ie:)
 else
   real_part     = real_string
   exponent_part = ' '
 end if
!
 do i = len_trim(real_part),1,-1
   if (real_part(i:i) /= '0') exit
 end do
!
 if (index(real_part, '.') > 0) real_string = real_part(:i) // exponent_part
! 
end subroutine trim_real_string 

John

14 Nov 2011 3:24 #9219

Quoted from christyleomin

Please advise how to represent only 20 characters in '7.500000000000000E-2' such that the correct real number is obtained.

Neither 4-byte nor 8-byte IEEE floating point formats can represent 0.075 exactly.

In hex, the number is either Z'3BF5C28F' (32-bit) or Z'3FB3333333333333' (64-bit).

In general, when such numbers are read and printed from source code, compiled and run, there is no guarantee that the output number will match the input number in decimal representation.

Please login to reply.