Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a random positive or negative decimal?

Tags:

php

random

How can I regenerate random decimal from -0.0010 to 0.0010 with php rand() or some other method?

like image 754
davidlee Avatar asked Jul 08 '10 17:07

davidlee


People also ask

How do you generate random decimals?

1. Select a blank cell, and type =RAND() into it, and then drag the fill handle to fill the range you need with the formula. 2. Then select the range you have applied the formula, and click the Increase Decimal button or Decrease Decimal button under Home tab to specify the decimal numbers.

How do you make a random number negative?

The correct code is int rand = new Random(). nextInt((30 - 20) + 1) + 20; . "It will return a random number between 30 and 20" - nope... @alfasin I was going to say the same thing.

How do you make a random number negative in Excel?

Randomize negative integer numbers The formula =RANDBETWEEN(X,Y) also can insert negative integer numbers. (X and Y indicate any negative numbers, and X<Y), here, I type =RANDBETWEEN(-120,-20) into a blank cell and press Enter key, then if you need, you can drag the fill handle to fill a range.


2 Answers

Divide rand() by the maximum random numer, multiply it by the range and add the starting number:

<?php
  // rand()/getrandmax() gives a float number between 0 and 1
  // if you multiply it by 0.002 you'll get a number between 0 and 0.002
  // add the starting number -0.001 and you'll get a number between -0.001 and 0.001

  echo rand()/getrandmax()*0.002-0.001;
?>
like image 102
Harmen Avatar answered Nov 03 '22 01:11

Harmen


.

$val = (rand(0,20)-10)/10000;
like image 42
nathan Avatar answered Nov 03 '22 01:11

nathan