Re: Fractional part of decimal value.

Jan Wielemaker <[email protected]>
Newsgroups gmane.comp.ai.prolog.swi
Message-ID <[email protected]>
On 08/07/2013 04:38 PM, Wouter Beek wrote:
> Hi Paulo,
>
> Thanks for the response! The functions that you mention have the same
> outcome:
> ~~~
> ?- X is float_fractional_part(1.1).
> X = 0.10000000000000009.
> ~~~
> Even:
> ~~~
> ?- X is 1.1 - 1.
> X = 0.10000000000000009.

Yes.  And they actually use C's modf() :-)  Change your program a little:

#include <stdio.h>
#include <math.h>

int main() {
   double param, fractional_part, integer_part;
   param = 1.1;
   fractional_part = modf(param, &integer_part);
   printf("%.25f = %.25f + %.25f \n", param, integer_part, fractional_part);
   return 0;
}

and we get

hppc823 (~) 8_> gcc -o f f.c
hppc823 (~) 9_> ./f
1.1000000000000000888178420 = 1.0000000000000000000000000 + 
0.1000000000000000888178420

That looks more like Prolog's outcome.  Now,

?- 0.1 =:= 0.1000000000000000888178420.
false.

While

2 ?- 1.1 =:= 1.1000000000000000888178420.
true.

SWI-Prolog's write/1 writes floats with a few as possible digits
that makes =:= succeed with the original value.  So, the claim is
that this is true for any float (where read and write nicely read
and write to/from the same file of course).

	write(X), read(Y), X=:=Y.

Possibly format/3 using ~f can help to accomplish your goal?
Floats are incredibly difficult to understand, especially
binary floats :-(

	Cheers --- Jan






> ~~~
> I understand that most decimal fractions cannot be represented by binary
> fractions, so there is probably a good reason to have the '9' appear at the
> end.
>
> My question is whether this can be circumvented for my simple/naive use.
> (Preferably a solution that does not involve a hack such as using
> format-to-codes and then number_codes/2 :-P.)
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.