chillpenguin
chillpenguin

Reputation: 3079

How to convert floats into compound fractions with specific denominators?

I need to convert floats into numbers that resemble measurements from a ruler. For example: 3.75 needs to be converted into 3 and 3/4. However, this is harder than it would seem at first, because I need to keep the denominator in a form that is easily translated into a ruler measurement by a human. Essentially, the denominator should only be powers of 2, up to 16. I don't want a fraction like 3/5 because 5'ths aren't marked on a ruler. I have figured out how to limit the denominator from going above 16, but I can't figure out how to keep the denominator a power of 2.

Answers in python or c++ is preferred.

Upvotes: 1

Views: 139

Answers (2)

chillpenguin
chillpenguin

Reputation: 3079

I did what Jhecht said because it seemed easy to do with python dictionary.

Upvotes: 0

Robert Dodier
Robert Dodier

Reputation: 17576

  • extract integer part, so you have fraction part less than 1.
  • find nearest 16th of fraction: multiply by 16 and round to nearest integer. Have some policy to break ties (e.g. round to even). I believe this step can't introduce floating point arithmetic error because you are multiplying by a power of 2.
  • reduce n/16 to lowest terms (cancel out common multiples of 2). I guess you need to compute the greatest common divisor. In Python that's fractions.gcd, dunno about C++.

Upvotes: 2

Related Questions