util.jl (2112B)
1 #!/usr/bin/env julia 2 3 export randpower 4 """ 5 randpower([nvals], [distribution_power], [min_val], [max_val]) 6 7 Returns one or more random numbers from a power-law probability distribution. 8 9 # Arguments 10 * `dims::Any`: the dimensions of random values (default = 1) 11 * `distribution_power::Number`: the distribution power (default = 1.) 12 * `min_val::Number`: the lower bound of the distribution range (default = 0.) 13 * `max_val::Number`: the upper bound of the distribution range (default = 1.) 14 """ 15 @inline function randpower(dims::Any = 1, 16 distribution_power::Number = 1., 17 min_val::Number = 0., 18 max_val::Number = 1.) 19 20 val = ((max_val^(distribution_power + 1.) - 21 min_val^(distribution_power + 1.)) * rand(Float64, dims) .+ 22 min_val^(distribution_power + 1.)) .^ 23 (1. / (distribution_power + 1.)) 24 25 if dims == 1 26 return val[1] 27 else 28 return val 29 end 30 end 31 32 export harmonicMean 33 """ 34 harmonicMean(a, b) 35 36 Returns the harmonic mean of two numbers `a::Number` and `b::Number`. 37 """ 38 function harmonicMean(a::Number, b::Number)::Number 39 if a ≈ 0. && b ≈ 0 40 return 0. 41 else 42 return 2. * a * b / (a + b) 43 end 44 end 45 46 export vecTo3d 47 """ 48 function vecTo3d(input, fill) 49 50 Convert a scalar or 2d vector to 3d by filling the missing component with the 51 value `fill`. The returned 3-component vector is a Vector (or 1d Array) of 52 the same type as the input. 53 54 # Arguments 55 * `input`: a scalar or two-component vector. 56 * `fill::Real`: value to use for third 57 """ 58 function vecTo3d(input::Any; fill::Real = 0.0) 59 if length(input) > 3 60 error("vecTo3d requires a scalar or input vector to of length 3 or " * 61 "less, but input is $input") 62 elseif length(input) == 3 63 return input 64 elseif length(input) == 2 65 return [input[1], input[2], typeof(input[1])(fill)] 66 elseif length(input) == 1 67 return [input[1], typeof(input[1])(fill), typeof(input[1])(fill)] 68 else 69 error("input not understood: $input") 70 end 71 end 72