Quantcast
Channel: Active questions tagged ruby - Stack Overflow
Viewing all articles
Browse latest Browse all 4610

Probability of getting specific sum after rolling n dice. Ruby

$
0
0

What is the best solution for finding probability of rolling sum with n dice?I'm solving it by finding

  1. mean.
  2. standard deviation.
  3. z_score for the numbers below x
  4. z_score for the numbers above x
  5. converting both to probabilities
  6. subtracting one from the other

This is what I've done so far.

# sides - number of sides on one diedef get_mean(sides)  (1..sides).inject(:+) / sides.to_fenddef get_variance(sides)  mean_of_squares = ((1..sides).inject {|sum, side| sum + side ** 2}) / sides.to_f  square_mean = get_mean(sides) ** 2  mean_of_squares - square_meanenddef get_sigma(variance)  variance ** 0.5end# x - the number of points in questiondef get_z_score(x, mean, sigma)  (x - mean) / sigma.to_fend# Converts z_score to probabilitydef z_to_probability(z)  return 0 if z < -6.5  return 1 if z > 6.5  fact_k = 1  sum = 0  term = 1  k = 0  loop_stop = Math.exp(-23)  while term.abs > loop_stop do    term = 0.3989422804 * ((-1)**k) * (z**k) / (2*k+1) / (2**k) * (z**(k+1)) / fact_k    sum += term    k += 1    fact_k *= k  end  sum += 0.5  1 - sumend# Calculate probability of getting 'х' total points by rolling 'n' dice with 'sides' number of sides.def probability_of_sum(x, n, sides=6)  mean = n * get_mean(sides)  variance = get_variance(sides)  sigma = get_sigma(n * variance)  # Rolling below the sum  z1 = get_z_score(x, mean, sigma)  prob_1 = z_to_probability(z1)  # Rolling above the sum  z2 = get_z_score(x+1, mean, sigma)  prob_2 = z_to_probability(z2)  prob_1 - prob_2end# Run probability for 100 diceputs probability_of_sum(400, 100)

What concerns me is, when I pick x = 200, the probability is 0.Is this correct solution?


Viewing all articles
Browse latest Browse all 4610

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>