home *** CD-ROM | disk | FTP | other *** search
/ ftp.cs.arizona.edu / ftp.cs.arizona.edu.tar / ftp.cs.arizona.edu / icon / historic / v941.tgz / icon.v941src.tar / icon.v941src / ipl / progs / fract.icn < prev    next >
Text File  |  2000-07-29  |  2KB  |  81 lines

  1. ############################################################################
  2. #
  3. #    File:     fract.icn
  4. #
  5. #    Subject:  Program to approximate real number as a fraction
  6. #
  7. #    Author:   Ralph E. Griswold
  8. #
  9. #    Date:     October 26, 1999
  10. #
  11. ############################################################################
  12. #
  13. #   This file is in the public domain.
  14. #
  15. ############################################################################
  16. #
  17. #  This program produces successive rational approximations to a real
  18. #  number.
  19. #
  20. #  The options supported are:
  21. #
  22. #    -n r    real number to be approximated, default .6180339887498948482
  23. #           (see below)
  24. #
  25. #    -l i    limit on number of approximations, default 100 (unlikely to
  26. #           be reached).
  27. #
  28. ############################################################################
  29. #
  30. #  This program was translated from a C program by Gregg Townsend.  His
  31. #  documentation includes the following remarks.
  32. #   rational mode based on a calculator algorithm posted by:
  33. #
  34. #     Joseph D. Rudmin  (duke!dukempd!jdr)
  35. #     Duke University Physics Dept.
  36. #     Aug 19, 1987
  37. #   n.b. for an interesting sequence try "fract .6180339887498948482".
  38. #   Do you know why?  (Hint: "Leonardo of Pisa").
  39. #
  40. ############################################################################
  41. #
  42. #  Links:  options
  43. #
  44. ############################################################################
  45.  
  46. link options
  47.  
  48. $define Epsilon 1.e-16    # maximum precision (more risks overflow)
  49.  
  50. procedure main(args)
  51.    local v, t, x, y, a, d, i, j, ops, opts, limit
  52.  
  53.    opts := options(args, "n.l+")
  54.  
  55.    v := \opts["n"] | .6180339887498948482
  56.    limit := \opts["l"] | 100
  57.  
  58.    x := list(limit + 2)
  59.    y := list(limit + 2)
  60.  
  61.    t := v
  62.  
  63.    every i := 1 to limit do {
  64.       x[i + 1] := integer(t)
  65.       y[i + 1] := 1
  66.       y[i + 2] := 0
  67.       every j := i - 1 to 0 by -1 do
  68.          y[j + 1] := x[j + 2] * y[j + 2] + y[j + 3]
  69.       a := real(integer(y[1])) / integer(y[2])
  70.       if a < 0 then exit()
  71.       write(integer(y[1]), " / ", integer(y[2]), " \t",  a)
  72.       if abs(a - v) < Epsilon then exit()
  73.       d := t - integer(t)
  74.       if d < Epsilon then exit()
  75.       t := 1.0 / d
  76.       }
  77.  
  78. end
  79.