Precision, new prices
downs
default_357-line at yahoo.de
Sat Jul 25 05:07:08 PDT 2009
Saaa wrote:
> I thought my previous precision question was so retarded it didn't need any
> explanation; anybody here could easily tell me my fault in reasoning.
>
> Here is my question again but this time with examples.
>
> Is there some formatting which lets me print out a floating point in full
> precision?
>
> Observation: 6 digits is not full precision:
>
> float f=3.4028234; // 0x7f7f ffff
> writefln("%.8g",f); // prints 3.4028234
> writefln(f.dig); // prints 6
> writefln(3.4028234f.dig); // prints 6
>
> Shouldn't f.dig print out 8?
> .dig = number of decimal digits of precision
>
> I still think I don't get something, somewhere.
>
>
Here's an incredibly simple hack.
import std.stdio, std.string;
string ftoaFull(float f) {
if (f < 0) return "-" ~ ftoaFull(-f);
auto start = f;
auto res = toString(cast(int) f) ~ ".";
while (true) {
f -= cast(int) f;
f *= 10;
res ~= "0123456789"[cast(int) f];
// The critical step
if (res.atof() == start) return res;
if (res.length > 32) {
writefln("Cannot find string representation for ", start, ", parses as ", res.atof(), ", delta ", res.atof() - start);
return res;
}
}
}
void main() {
writefln(ftoaFull(0f));
writefln(ftoaFull(-5.234));
writefln(ftoaFull(1f / 3f)); // problematic
}
Output:
0.0
-5.2340002059936523437
Cannot find string representation for 0.333333, parses as 0.333333, delta 5.96046e-09
0.3333333492279052734375000000000
And there you have it.
More information about the Digitalmars-d-learn
mailing list