Python Forum
comparing fractional parts of floats
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
comparing fractional parts of floats
#5
Starting with an example that fails the "multiply by 10" approach:

>>> math.modf(22.7)[0]*10
6.999999999999993
You can use the fractions module:

Note: the following fails when the denominator is either 1, 2 or 5.

>>> from fractions import Fraction
>>> Fraction(22.7)
Fraction(6389481971331891, 281474976710656)
>>> Fraction(22.7).limit_denominator(10)
Fraction(227, 10)
>>> a=Fraction(22.7).limit_denominator(10)
>>> divmod(a.numerator, a.denominator)
(22, 7)
The following version should handle the cases when the denominator is not 10. It also uses the output of modf directly.

>>> a=Fraction(math.modf(22.7)[0]).limit_denominator(10)
>>> divmod(10,a.denominator)[0]*a.numerator
7
Reply


Messages In This Thread
comparing fractional parts of floats - by Skaperen - Mar-18-2019, 07:31 PM
RE: comparing fractional parts of floats - by casevh - Mar-19-2019, 03:19 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  When is it safe to compare (==) two floats? Radical 4 732 Nov-12-2023, 11:53 AM
Last Post: PyDan
  floats 2 decimals rwahdan 3 1,630 Dec-19-2021, 10:30 PM
Last Post: snippsat
  rounding and floats Than999 2 3,108 Oct-26-2020, 09:36 PM
Last Post: deanhystad
  int, floats, eval menator01 2 2,446 Jun-26-2020, 09:03 PM
Last Post: menator01
  Stuck comparing two floats Tizzle 7 3,050 Jun-26-2020, 08:23 AM
Last Post: Tizzle
  rounding floats to a number of bits Skaperen 2 2,317 Sep-13-2019, 04:37 AM
Last Post: Skaperen
  Integer vs Floats Tazbo 2 2,875 Jan-09-2019, 12:06 PM
Last Post: Gribouillis
  Formatting floats Irhcsa 6 4,171 Oct-04-2018, 04:23 PM
Last Post: volcano63
  How do you sort a table by one column?? (of floats) sortedfunctionfails 3 12,311 Jan-11-2018, 09:04 AM
Last Post: sortedfunctionfails
  Reading floats and ints from csv-like file Krookroo 15 20,078 Sep-05-2017, 03:58 PM
Last Post: Krookroo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020