3

Say, I write down in a programming language the characters 5.4 and store it into a double variable. How exactly does a computer decide what floating point representation (mantissa and exponent) is the closest to that number?

Michiel Borkent
  • 34,228
  • 15
  • 86
  • 149
  • Lovely question, but I think it might belong to a different SE site. – Ramon Snir Sep 08 '11 at 08:55
  • the question is asked often: see for example http://stackoverflow.com/questions/85223/how-to-manually-parse-a-floating-point-number-from-a-string/85526#85526 – Matteo Sep 08 '11 at 09:04

2 Answers2

1

Well, the compiler or interpreter of the programming language uses an algorithm to convert from a decimal string representation to a (binary) floating point representation.

One implementation is David Gay's strtod() at http://www.netlib.org/fp/dtoa.c .

Note that while Gay's code is the basis for many implementations of strtod() and snprintf() in widely used C libraries, the code as such suffers from a number of issues and should not be used as such. But, it's instructive as a self-contained example.

janneb
  • 36,249
  • 2
  • 81
  • 97
1

I once described this, in a simple, easily understood way, for the value 5.2, see this SO article.

Community
  • 1
  • 1
Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94