Search code examples
cpi

Stream hex number as decimal


I would like to use the BBP formula to calculate Pi in a C-program's pthread process while another process prints the result for as far as it has got. However BBP gives a base 16 answer while I would like to stream a base 10 answer to the user.

How can I determine whether it's safe to print the n-th digit of a base 10 converted base 16 number?

Thanks in advance!


Solution

  • One solution is to test whether increasing the last hexadecimal digit currently available changes the decimal digit you are considering displaying.

    Consider a number x with hexadecimal representation …h3h2h1h0.h-1h-2… and decimal representation …d3d2d1d0.d-1d-2

    Suppose we have a truncated numeral, so that we know only the digits from h to hj. Let y be the number represented by these digits. Let z be y + 16j, which is y plus one in the j digit position. Then the value of x might be any value from y (inclusive) to z (exclusive).

    Now consider a candidate decimal numeral, with digits d to di. Let y' be the number represented by these digits. Let z' be y + 10i. Iff y' ≤ y and z ≤ z', then the decimal digits d to di must be a prefix of the complete decimal numeral for x (that is, these decimal digits are known to appear in the decimal numeral for x; they will not change as more hexadecimal digits are discovered).

    This is because the value of x, being in [y, z), can be formed by adding some zero or positive value to y' and that value needed is less than 1 in the i digit position. Conversely, if the inequalities do not hold, then x could be outside the interval spanned by the candidate digits.