Append a real number, in JSON syntax, in double precision (also when wp is
quad precision: the trajectory files are for plotting and SPK files, which are
double precision), with 17 significant digits
(e.g., 8.2031911203980994E+8; trailing zeros are removed, e.g. 1.5E+0).
The 17 digits are correctly rounded, so the number reads back as exactly the
same double precision value. |x| is scaled to a 17-digit integer by an exact
power of ten (), and the rounding error of that product
(or quotient) is computed exactly (Dekker's two-product), so the integer is the
correctly rounded one. Numbers too small or too large for this
(|x| < 1e-6 or |x| >= 1e39) are formatted with a write statement instead.
Non-finite numbers are written as null, since JSON has no NaN or Infinity.
| Type | Intent | Optional | Attributes | Name | ||
|---|---|---|---|---|---|---|
| class(text_buffer), | intent(inout) | :: | me | |||
| real(kind=wp), | intent(in) | :: | x |
the number (converted to double precision, if |
pure subroutine add_real(me, x) class(text_buffer),intent(inout) :: me real(wp),intent(in) :: x !! the number (converted to double precision, if `wp` is not) integer(int64),parameter :: ten16 = 10000000000000000_int64 !! 10^16 integer(int64),parameter :: ten17 = 10_int64*ten16 !! 10^17 real(dp) :: xd, ax integer :: e10, i, last integer(int64) :: im logical :: ok character(len=17) :: digits character(len=30) :: str xd = real(x, dp) if (.not. ieee_is_finite(xd)) then call me%add_str('null') return end if if (xd == 0.0_dp) then call me%add_str('0.0') return end if ! im = |x| * 10^(16-e10), rounded, should have 17 digits: ax = abs(xd) e10 = floor(log10(ax)) call scaled(ax, 16-e10, im, ok) ! (log10 may be off by one near powers of ten) if (ok .and. im >= ten17) then e10 = e10 + 1 call scaled(ax, 16-e10, im, ok) else if (ok .and. im < ten16) then e10 = e10 - 1 call scaled(ax, 16-e10, im, ok) end if if (ok .and. im == ten17) then ! rounded up to the next power of ten (e.g., 9.99999999999999999) im = ten16 e10 = e10 + 1 end if if (.not. ok) then ! out of the range of the exact powers of ten: write(str,'(ES24.16E3)') xd call me%add_str(trim(adjustl(str))) return end if ! the 17 digits: do i = 17, 1, -1 digits(i:i) = achar(iachar('0') + int(mod(im, 10_int64))) im = im / 10_int64 end do ! remove the trailing zeros (keeping at least one digit after the decimal point): last = 17 do while (last > 2 .and. digits(last:last) == '0') last = last - 1 end do call me%reserve(30) if (xd < 0.0_dp) call me%add_str('-') call me%add_str(digits(1:1)//'.'//digits(2:last)//'E') if (e10 >= 0) call me%add_str('+') call add_digits(me, int(e10,int64), negative=e10<0) end subroutine add_real