1

How can I convert z-score to probability using ruby?

Example:

z_score = 0
probability should be 0.5

z_score = 1.76
probability should be 0.039204
Pav31
  • 540
  • 7
  • 19

1 Answers1

5

According to this https://stackoverflow.com/a/16197404/1062711 post, here is the function that give you the p proba from the z score

def getPercent(z)
  return 0 if z < -6.5
  return 1 if z > 6.5

  factk = 1
  sum = 0
  term = 1
  k = 0

  loopStop = Math.exp(-23)
  while term.abs > loopStop do
      term = 0.3989422804 * ((-1)**k) * (z**k) / (2*k+1) / (2**k) * (z**(k+1)) /factk
      sum += term
      k += 1
      factk *= k
  end

  sum += 0.5
  1-sum
end

puts getPercent(1.76)
Community
  • 1
  • 1
ex0ns
  • 1,116
  • 8
  • 19
  • Wow, nice! But isn't it should be `return 1 if z < -6.5` and `return 0 if 6.5 < z`? – Zhomart Feb 04 '16 at 23:52
  • 1
    Am I the only Rubyist who finds it frustrating that this is [so much easier in Python](https://stackoverflow.com/questions/20864847/probability-to-z-score-and-vice-versa-in-python). This otherwise fine language still sports a `Math` module with a paltry 26 methods. Come on ruby-lang.org, it's about time to expand this - & a `Math::Stats` module in the Std-lib would be nice too. – MatzFan Jun 22 '17 at 18:20