How to convert real number into fraction

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Andrew Esmundo

    How to convert real number into fraction

    Im trying to write a program for c that promts the user for a non-negative real number and outputs the fraction closest to that number. For example: if I input 42.7488 the the output is 171/4. Would I use an if loop? Would it be correct to change the real number into an integer and find the greatest common denominator?
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    Start with finding a mathematical algorithm for this. Don't worry about writing a computer program until after that.

    Did your teacher provide any hints or suggestions for what algorithm to use?

    By the way, I think what you're trying to do is find a rational approximation for a real number. The word fraction is ambiguous.

    Comment

    • newb16
      Contributor
      • Jul 2008
      • 687

      #3
      Unless the number is rational, there is no such thing as "the closest" one, otherwise the number itself is the closest. You need to set some precision and stop after it's reached ( in the example it's 0.0012)
      e.g.
      for each i from 2
      N = [x*i]; if N/i or (N+1)/i is close enough then stop;

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        171/4 is certainly not the closest rational approximation to 42.7488. What is your criteria for best and/or close enough?

        171/4 = 42.75
        but 427488/10000 is precisely 42.7488
        (and the latter ratio can be reduced to 26718/625)
        What is it that makes the first ratio better than either of the two exact forms?

        Comment

        Working...