daily pastebin goal
41%
SHARE
TWEET

Untitled

a guest Dec 9th, 2018 46 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from __future__ import division
  2. from random import random
  3. from math import floor
  4.  
  5. def fractionize(R, n, d):
  6.     error = abs(n/d - R)
  7.     return (n, d, error)  # (numerator, denominator, absolute difference to R)
  8.  
  9. def better(a, b):
  10.     return a if a[2] < b[2] else b
  11.  
  12. def approximate(R, n, m):
  13.     best = (0, 1, R)
  14.     for d in xrange(1, m+1):
  15.         n1 = min(n, int(floor(R * d)))
  16.         n2 = min(n, n1 + 1) # ceil(R*d)
  17.         best = better(best, fractionize(R, n1, d))
  18.         best = better(best, fractionize(R, n2, d))
  19.     return best
  20.  
  21. if __name__ == '__main__':
  22.     def main():
  23.         R = random()
  24.         n = 30
  25.         m = 100
  26.         print R, approximate(R, n, m)
  27.     main()
  28.    
  29. best_x,best_y=(1,1)
  30. for x in 1...n:
  31.     y=max(1,min(m,round(x/R)))
  32.     #optional optimization (if you have a fast gcd)
  33.     if gcd(x,y)>1:
  34.         continue
  35.  
  36.     if abs(R-x/y)<abs(R-bestx/besty):
  37.         best_x,best_y=(x,y)
  38. return (best_x,best_y)
  39.    
  40. r: input number to search.
  41. n,m: the ranges.
  42.  
  43. for (int i=1;i<=m;i++)
  44. {
  45.     minVal = min(Search(i,1,n,r), minVal);
  46. }
  47.  
  48. //x and y are start and end of array:
  49. decimal Search(i,x,y,r)
  50. {
  51.    if (i/x > r)
  52.       return i/x - r;
  53.  
  54.    decimal middle1 = i/Cill((x+y)/2);
  55.    decimal middle2 = i/Roof((x+y)/2);
  56.  
  57.    decimal dist = min(middle1,middle2)
  58.  
  59.    decimal searchResult = 100000;
  60.  
  61.    if( middle > r)
  62.      searchResult = Search (i, x, cill((x+y)/2),r)
  63.   else
  64.      searchResult = Search(i, roof((x+y)/2), y,r)
  65.  
  66.   if  (searchResult < dist)
  67.      dist = searchResult;
  68.  
  69.   return dist;
  70. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top