in reply to Re^2: subtraction issue
in thread subtraction issue

Previous to Perl version 5.22.0, you can use a format like '%0.20f'

Yes, I think that's a good enough replacement for most purposes - and a useful addition to my post.

However, it's not guaranteed to give you the exact base 10 value stored in the double - whereas %a will give you the exact (base 16) value.

Cheers,
Rob

Replies are listed 'Best First'.
Re^4: subtraction issue
by pryrt (Abbot) on Jan 27, 2017 at 16:41 UTC

    Feel free to ignore this post. I just couldn't help myself (I needed the coffee-break distraction, apparently)

      it takes n fixed-point decimal digits to exactly represent an n-bit fixed-point fractional binary number

      Thank you for correcting me ... but shouldn't that be "n+1 fixed-point decimal digits" ?
      use strict; use warnings; use Math::MPFR qw(:mpfr); Rmpfr_set_default_prec(1000); my $d = 1 / 11; my $x = Math::MPFR->new($d); print "$x\n", length($x), "\n"; # (print() removes trailing zeros.) # Outputs: 9.09090909090909116141432377844466827809810638427734375e-2 58
      Take out the "." and the "e-2" and we're left with 54 decimal digits.

      Cheers,
      Rob

        That's confusing to me, because the math says that for a fraction that's exactly representable with d digits after the binary point, f = m * 2**-d = m * 5**d / (5**d * 2**d) = m * 5**d / 10**d, which is exactly representable with d digits after the decimal point, because m * 5**d is an integer, and an integer over 10**d only needs d digits after the decimal point: 17 / 10**5 = 0.00017.

        I will try to find some time this weekend to see what's going on. 1/11 isn't exactly representable in binary, but assuming that mpfr is using the exact value of the double precision, I would think it would fit in the 52 digits after the point. Oh, wait! The 52 is actually the digits of the fraction of the mantissa after removing enough powers of 2 to get the mantissa between 1 and 2. So internally, it would be 1.4545... * 2**-4. So we've got 52 binary digits after the double floating point, plus four more digits due the power of two, which makes d = 58: the 54 SIG figs you show, plus the 2 zeroes from e-2, plus apparently 2 zeroes after the final 5 shown. (This would have been so much easier if I were at a computer with perl, not just my tablet and my emulator in my skull...)