• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 647
  • Last Modified:

generate random between min/max with step value

I need to create a function that takes 3 parameters "min", "max", "step" the purpose of it is to generate a random number between min-max, but in increments of "step"
For example get_random(1,3,0.5) would return a single value of {1.0, 1.5, 2.0, 2.5, 3.0}

The "step" value can be pretty much anything (1, 2, 0.001).

Appreciate any help.
0
Coffinated
Asked:
Coffinated
  • 2
  • 2
  • 2
2 Solutions
 
hieloCommented:
try:


function get_random($mi,$ma,$st){
 $result=array();
 for( $i=$mi; $i<$ma; $i+=$st)
 {
  $result[]=$i;
 }
return $result;
}

Open in new window

0
 
gr8gonzoConsultantCommented:
I'm not sure where it's random - are you looking to generate a random STARTING number between those values and increment from there? For example, if you ran your get_random(1,3,0.5) four times, what would the output look like on each of those 4 runs?
0
 
CoffinatedAuthor Commented:
clarification:
returned value can be any number from {1.0, 1.5, 2.0, 2.5, 3.0}, for example 2.0

hielo:

That will almost work, returned value needs to be a random number from the array.
$total = count($result);
return $result[rand(0, $total)];

That's was the function I had in mind, I was hoping for something more sophisticated in PHP, but it'll do just fine.
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
gr8gonzoConsultantCommented:
Ah I understand now. Try this:

<?php
function get_random($min,$max,$step)
{
  $numSteps = ($max-$min)/$step;
  $multiplier = rand(0,$numSteps);
  $num = $min + ($multiplier * $step);
  return $num;
}
?>
0
 
hieloCommented:
>>returned value needs to be a random number from the array.
Ah, OK. That was not clear from what you posted :)

You obviously figured out the extra code to get that random number.

Regards,
Hielo
0
 
CoffinatedAuthor Commented:
Thank you, both solutions work, however gr8gonzo's is more efficient.
0

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

  • 2
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now