如何生成一个随机的正或负小数? [英] How to generate a random positive or negative decimal?

查看:121
本文介绍了如何生成一个随机的正或负小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用php rand()或其他方法将随机小数从-0.0010再生为0.0010?

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

推荐答案

rand()除以最大随机数,再乘以范围,然后加上起始数字:

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;
?>

这篇关于如何生成一个随机的正或负小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆