Home > Backend Development > PHP Tutorial > PHP method to generate random decimals from 0 to 1

PHP method to generate random decimals from 0 to 1

墨辰丷
Release: 2023-03-27 18:38:01
Original
2114 people have browsed it

This article mainly introduces the method of generating 0~1 random decimals in PHP. Interested friends can refer to it. I hope it will be helpful to everyone.

The method for Javascript to generate random decimals from 0 to 1 can call the built-in Math.random();

For example:

<script type="text/javascript">
document.write(Math.random()); // 0.5840498607140034
</script>
Copy after login

There are rand,mt_rand random methods in php, but neither of these two methods can generate 0~1 random decimal, we can write a method to implement this function.

The method for php to generate random decimals from 0 to 1 is as follows:

<?php
/**
 * 生成0~1随机小数
 * @param Int  $min
 * @param Int  $max
 * @return Float
 */
function randFloat($min=0, $max=1){
  return $min + mt_rand()/mt_getrandmax() * ($max-$min);
}

// 例子,创建5个0~1随机小数
for($i=0; $i<5; $i++){
  echo randFloat().&#39;<br>&#39;;
}
?>
Copy after login

Output:

0.59804026251568
0.67772196544228
0.90589751205682
0.45087858822703
0.17475316774787
Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone's study.


Related recommendations:

PHPDetermine whether a file exists in the specified directory

Php, MySQL environment configuration

PHPFunction curl request-fetch page/interface test

The above is the detailed content of PHP method to generate random decimals from 0 to 1. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template