OT: Re: is dwt alive?

"Jérôme M. Berger" jeberger at free.fr
Mon Jul 12 11:18:26 PDT 2010

aarti_pl wrote:
> W dniu 2010-07-11 23:39, aarti_pl pisze:
>> W dniu 2010-07-11 22:45, "Jérôme M. Berger" pisze:
>>> aarti_pl wrote:
>>>> I just would like to say that it is a great news! After discovering
>>>> that
>>>> for Java:
>>>> ----
>>>> double sum = 0.0;
>>>> for (int i = 0; i< 10; i++) sum += 0.1;
>>>> ----
>>>> sum is equal: 0.9999999999999999
>>>> I am looking at D with greater and greater sentiment :-) SWT and good
>>>> precision of calculations is necessary for my program...
>>> Are you sure D is better? In C, you get 0.99999999999999988898 (not
>>> surprising since 0.1 cannot be represented exactly in base 2) and I
>>> would expect D to give the same result...
>>> Jerome
>> On my computer it is exactly 1.0 (one).
>> I know that there is explanation of why it is like that, as I found
>> article about it. I did not get deeper into it (good few pages of text)
>> as I believe there must better solution for programmers.
>> My calculator shows proper results, spreadsheet shows proper results and
>> I think that calculations in my program for such a big fractions should
>> also give correct result.
>> Just thought: maybe calculations in D are done internally in more than
>> 64bits and then casted into 64bits? It's a bit surprising for me that C
>> is also wrong about this sum...
>> BR
>> Marcin Kuszczak
>> (aarti_pl)
> Ok. You are right. D is not better in this case. It seems that it's just
> writeln cut number of decimal digits and printed 1.
> Using:
> writefln("%.25f", sum);
> we get:
> 0.99999999999999988897
> Does it mean that the only way to get better precision is to use some
> custom classes like BigDecimal in Java?
	AFAIK, yes. The problem is that 0.1 cannot be represented exactly
in base 2, no matter what precision you use. So your choices are
(from fastest to slowest):

- decide that the precision of a double is enough for your
application after all;

- use some arbitrary precision library like gmp to increase
precision, being aware that no matter how much you increase the
precision, the loop above will *never* give 1 (although it can come
close enough that conversion to a double will give 1)

- use some symbolic computations library. This will give you
absolute precision, but may be slow and won't always give you a
numerical result, i.e sqrt(2) is sqrt(2) and that's that, if you try
to get a numerical result out of it, then you wind up with the same
limitations as the other solutions.

mailto:jeberger at free.fr
Jabber: jeberger at jabber.fr

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 198 bytes
Desc: OpenPGP digital signature
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-dwt/attachments/20100712/9684dbd6/attachment.pgp>

More information about the Digitalmars-d-dwt mailing list