Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
whole number and fraction
#11
Using decimal.Decimal(float) or fractions.Fraction(float) is not right.
The float you see is wrong. The representation is binary and can't represent all decimal fractions.
Avoid using float as value for Decimal or Fraction.

Compare the results:
print(fractions.Fraction(3, 10)) #right
print(fractions.Fraction('0.3')) #right
print(fractions.Fraction(0.3)) # wrong
The last result is wrong, because the literal 0.3 is converted to a binary fraction, which is very close to 0.3, but it is not real 0.3.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#12
i think people just didn't "get" what i was trying to do. and i figured it out. the answer was pretty obvious. but i didn't think of it at first because of my background with C which has a library function to do it which i have used. i just wanted the non-whole part of a float value (or of a decimal.Decimal one, if that's what i get). i just get the whole value and subtract that from the original.
    whole = type(value)(int(value))
    fract = value-whole
but python actually does have a function that does this and returns a 2-tuple with both answers while C's equivalent (same name) returns the fractional part and stores the whole part via the pointer given argument two.
    fract,whole = math.modf(value)
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  method to remove zero digits from fraction in decimal Skaperen 17 2,695 Oct-23-2022, 04:02 AM
Last Post: Skaperen
  Fraction Calculation with Limitations TINMAN01 13 5,350 Dec-22-2020, 04:45 AM
Last Post: bowlofred
  fraction module: can you stop the reducing? qmfoam 1 2,392 Oct-10-2020, 06:10 PM
Last Post: bowlofred

Forum Jump:

User Panel Messages

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