• 🏆 Texturing Contest #33 is OPEN! Contestants must re-texture a SD unit model found in-game (Warcraft 3 Classic), recreating the unit into a peaceful NPC version. 🔗Click here to enter!
  • It's time for the first HD Modeling Contest of 2024. Join the theme discussion for Hive's HD Modeling Contest #6! Click here to post your idea!

Ruby Help Thread

Status
Not open for further replies.
Level 6
Joined
Apr 16, 2007
Messages
177
Code:
class Integer
  def choose( n )
    return self.fac / ( ( self - n).fac * n.fac )
  end
  def fac()    
    return 1 if self <= 1
    return self * (self-1).fac
  end
end
  
module BernoulliChain
  def bernoulli( n, p, k )
    return ( n.choose k ) * ( p ** k ) * ( 1 - p ) ** ( n - k )
  end

  def bernoulli_upto( n, p, k_max )
    a = 0
    0.upto( k_max ) do |k|
      a += bernoulli( n, p, k )
    end
    a
  end
  
end
 
Level 6
Joined
Apr 16, 2007
Messages
177
Code:
=begin
  This is a bernoulli chain module.
  A bernoulli chain is a chain of the
  same experiment that has only two 
  possible outcomes, and of which the 
  chances for one outcome stays the 
  same.
  Simply use
  bernoulli( n, p, k ) 
    to get the probability that 
    out of n experiments 
    k have the outcome 
    with a chance of p.
    
  and
  bernoulli_upto( n, p, k_max ) 
    to get the probability that 
    out of n experiments 
    upto k_max have the outcome 
    with a chance of p. 
  
  example:
   bernoulli( 2, 0.5, 2 )
    => the chance that, 
       when flipping two laplace coins,
       exactly 2 show heads (.25)
       
   bernoulli_upto( 2, 0.5, 2 )
    => the chance that, 
       when flipping two laplace coins,
       up to 2 (0,1, or 2 ) show heads (1.0)
    
=end
 
Level 6
Joined
Apr 16, 2007
Messages
177
Message was tooo long...
...twice!


The code above works perfectly. Is there anything to improve?
And how would I be able to implement the class chance into the module so that
Code:
include BernoulliChain
does implement the fac and choose( k ) methods for the integer class?
Or should I just write them as helper methods, like def choose( n, k ) and fac( n ) ?
It is possible to do that In a string that is then evaluated, but that Is really ugly :mad:

Thanks for any help, Davey

PS:
First post -> Code,
Second post -> Docu for the Code (due to limited message size I had to exclude it :/ )
 
Status
Not open for further replies.
Top