Re: Fractional part of decimal value.

Alan Baljeu <[email protected]>
Newsgroups gmane.comp.ai.prolog.swi
Message-ID <[email protected]>
Wouter, this is simple floating point error:

1 ?- X is 1.1-1.0.
X = 0.10000000000000009.

You cannot avoid these while you use floating point.  Neither 1.1 nor 0.1 have 
a finite binary representation, and when subtracting as you do, you lose a level 
of precision in your result.

I don't know about the C code, but I'll guess maybe it 
also has the 9 but the number isn't displayed to the same precision.

Probably your solution is to simply reduce the amount of decimals displayed.
Or use whole numbers or fractions.

Alan Baljeu


----- Original Message -----
From: Wouter Beek <[email protected]>
To: SWI-Prolog <[email protected]>
Cc: 
Sent: Wednesday, August 7, 2013 10:14:10 AM
Subject: [SWIPL] Fractional part of decimal value.

Hi all,

I want to extract the integer and fractional part of a decimal value:
~~~{.pl}
decimal_parts(D, I, F):-
  I is floor(D / 1),
  F is D - I * 1.
~~~
What I get is the fractional part of the float value 1.1:
~~~
?- decimal_parts(1.1, _, F).
F = 0.10000000000000009.
~~~
I do not mind the padding zero's (just a notational difference), but I do
not need the 9 at the end.

Is there a way to get the same result as with e.g. C's modf (sample code
below)? Thanks for any suggestions!

---
Cheers,
Wouter.

Sample code in C:
~~~{.c}
#include <stdio.h>
#include <math.h>

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

Compile and run:
~~~
$ gcc -Wall test.c -o test
$ ./test
1.100000 = 1.000000 + 0.100000
~~~

E-mail: [email protected]
WWW: www.wouterbeek.com
Tel.: 0647674624
-------------- next part --------------
HTML attachment scrubbed and removed
_______________________________________________
SWI-Prolog mailing list
[email protected]
https://lists.iai.uni-bonn.de/mailman/listinfo.cgi/swi-prolog
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.