Java中比較常用的幾個數學公式的總結:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
//取整,返回小于目標函數的最大整數,如下將會返回-2 Math.floor(- 1.8 ); //取整,返回發育目標數的最小整數 Math.ceil() //四舍五入取整 Math.round() //計算平方根 Math.sqrt() //計算立方根 Math.cbrt() //返回歐拉數e的n次冪 Math.exp( 3 ); //計算乘方,下面是計算3的2次方 Math.pow( 3 , 2 ); //計算自然對數 Math.log(); //計算絕對值 Math.abs(); //計算最大值 Math.max( 2.3 , 4.5 ); //計算最小值 Math.min(,); //返回一個偽隨機數,該數大于等于0.0并且小于1.0 Math.random |
Random類專門用于生成一個偽隨機數,它有兩個構造器:一個構造器使用默認的種子(以當前時間作為種子),另一個構造器需要程序員顯示的傳入一個long型整數的種子。
Random比Math的random()方法提供了更多的方式來生成各種偽隨機數。
e.g
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
import java.util.Arrays; import java.util.Random; public class RandomTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Random rand = new Random(); System.out.println( "隨機布爾數" + rand.nextBoolean()); byte [] buffer = new byte [ 16 ]; rand.nextBytes(buffer); //生產一個含有16個數組元素的隨機數數組 System.out.println(Arrays.toString(buffer)); System.out.println( "rand.nextDouble()" + rand.nextDouble()); System.out.println( "Float浮點數" + rand.nextFloat()); System.out.println( "rand.nextGaussian" + rand.nextGaussian()); System.out.println( "" + rand.nextInt()); //生產一個0~32之間的隨機整數 System.out.println( "rand.nextInt(32)" + rand.nextInt( 32 )); System.out.println( "rand.nextLong" + rand.nextLong()); } } |
為了避免兩個Random對象產生相同的數字序列,通常推薦使用當前時間作為Random對象的種子,代碼如下:
Random rand = new Random(System.currentTimeMillis());
在java7中引入了ThreadLocalRandom
在多線程的情況下使用ThreadLocalRandom的方式與使用Random基本類似,如下程序·片段示范了ThreadLocalRandom的用法:
首先使用current()產生隨機序列之后使用nextCXxx()來產生想要的偽隨機序列:
1
2
3
|
ThreadLocalRandom trand= ThreadLocalRandom.current(); int val = rand.nextInt( 4 , 64 ); |
產生4~64之間的偽隨機數
以上就是小編為大家帶來的基于Java中Math類的常用函數總結的全部內容了,希望對大家有所幫助,多多支持服務器之家~