Division - precision
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat May 21 15:44:42 PDT 2016
On 05/21/2016 02:45 PM, Rygel wrote:
> Hi there. I'm a beginners, so my questions could be silly.
>
> double x1 = 7.0;
> double x2 = 3.0;
> writeln(x1 / x2);
>
> from this code i get:
>
> 2.33333
>
> this is ok but how can i get more digits? For example:
>
> 2.333333333.....
>
> thx :-)
There are two kinds of precision to talk about in this case:
1) The value: You can't do anything about the precision other than
picking a more precise type. ('real' has more precision than 'double'.)
2) The display: You can display the value more precisely with a format
specifier like "%.10f" (with 10 digit precision):
import std.stdio;
import std.string;
void main() {
double x1 = 7.0;
double x2 = 3.0;
pragma(msg, format("%s has %s-digit precision",
double.stringof, double.dig));
writeln("Printing with too many digits:");
writefln("%.30f", x1 / x2);
static const betterFormatSpec = format("%%.%sf", double.dig);
writefln("Printing with just the right amount precision:");
writefln("(The format string used is \"%s\".)", betterFormatSpec);
writefln(betterFormatSpec, x1 / x2);
}
In any case, watch Don Clugston's DConf 2016 presentation as an
eye-opener and great entertainment:
http://www.ustream.tv/recorded/86406491/highlight/699207
Ali
More information about the Digitalmars-d-learn
mailing list