How can I regenerate random decimal from -0.0010 to 0.0010 with php rand()
or some other method?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
This will return any possible number between
-0.001
and+0.001
This uses two rand() calls but I think that the readability makes up for it tenfold. The first part makes either a -1 or +1. The second part can be anything between 0 and your limit for +/- numbers.
Unless you require LOTs of random numbers in a gigantic loop, you probably won't even notice the speed difference. I ran some tests (50.000 iterations) and it came up to around 0.0004 milliseconds to get a random number by my function. The alternatives are around half that time, but again, unless you are inside a really big loop, you are probably better of optimizing somewhere else.
Speed testing code:
Divide
rand()
by the maximum random numer, multiply it by the range and add the starting number:.