geometric-harmonic_mean.sf 763 B

123456789101112131415161718192021222324252627282930313233
  1. #!/usr/bin/ruby
  2. # Daniel "Trizen" Șuteu
  3. # Date: 17 March 2018
  4. # https://github.com/trizen
  5. # Geometric-harmonic mean (GHM).
  6. # If AGM(x,y) is the arithmetic-geometric mean, then GHM(x,y) is equivalent with:
  7. #
  8. # GHM(x,y) = 1/AGM(1/x, 1/y)
  9. #
  10. func GHM(g, h, p=100) {
  11. loop {
  12. var g1 = sqrt(g*h)
  13. var h1 = (2 / (1/g + 1/h))
  14. if (
  15. (g1.round(-p) == g.round(-p)) &&
  16. (h1.round(-p) == h.round(-p))
  17. ) {
  18. return g
  19. }
  20. (g, h) = (g1, h1)
  21. }
  22. }
  23. say GHM(1, 2) #=> 1.37288050061835016469763757500780605809453862535
  24. say GHM(1, 1/2) #=> 0.686440250309175082348818787503903029047269312674
  25. say GHM(3, 1/sqrt(2)) #=> 1.28640254813473954856043309974567498549916997311