On Wed, Dec 06, 2023 at 04:24:51AM +0900, confuzzled via Digitalmars-d-learn wrote: [...] > import std.stdio; > void main() > { > F fp; > fp.lo.writeln; // Why is this not zero? How is this value derived? > fp.hi.writeln; // expected > fp.x.writeln; // expected > > fp.x = > 19716939937510315926535.148979323846264338327950288458209749445923078164062862089986280348253421170679; > fp.lo.writeln; > fp.hi.writeln; > fp.x.writefln!"%20.98f"; // Also, why is precision completely lost after > 16 digits (18 if I change the type of x to real)? > } > > Sorry if this seem like noise but I genuinely do not understand. What > changes would I need to make to retain the precision of the value > provided in the assignment above? [...]
A `double` type is stored as an IEEE double-precision floating-point number, which is a 64-bit value containing 1 sign bit, 11 exponent bits, and 53 mantissa bits (52 stored, 1 implied). A mantissa of 53 bits can store up to 2^53 distinct values, which corresponds with log_10(2^53) ≈ 15.95 decimal digits. So around 15-16 decimal digits. (The exponent bits only affect the position of the decimal point, not the precision of the value, so they are not relevant here.) In D, you can use the .dig property to find out approximately how many of precision a format has (e.g., `writeln(double.dig);` or `writeln(real.dig);`). The number you have above is WAY beyond the storage capacity of the double-precision floating-point format or the 80-bit extended precision format of `real`. If you need that level of precision, you probably want to use an arbitrary-precision floating point library like libgmp instead of the built-in `double` or `real`. (Keep in mind that the performance will be significantly slower, because the hardware only works with IEEE 64-bit / 8088 80-bit extended precision numbers. Anything beyond that has to be implemented in software, and will incur memory management costs as well since the storage size of the number will not be fixed.) Also, if you don't understand how floating-point in computers work, I highly recommend reading this: https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html It's a bit long, but well worth the time to read to understand why floating-point behaves the way it does. T -- It is of the new things that men tire --- of fashions and proposals and improvements and change. It is the old things that startle and intoxicate. It is the old things that are young. -- G.K. Chesterton