Java中Math类常用函数总结
来源:互联网 发布:农村淘宝下载官网 编辑:程序博客网 时间:2024/05/29 23:45
Java中比较常用的几个数学公式的总结:
//取整,返回小于目标函数的最大整数,如下将会返回-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
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()来产生想要的伪随机序列:
ThreadLocalRandom trand= ThreadLocalRandom.current(); int val = rand.nextInt(4,64);
产生4~64之间的伪随机数
本文地址:http://liuyanzhao.com/3150.html
转载请注明
0 0
- Java中Math类常用函数总结
- 【Java中Math类常用函数总结】
- Java中Math类常用函数总结
- Java中常用math函数
- java数学函数Math类中常用的方法
- java数学函数Math类中常用的方法
- Java中Math的常用函数
- java中Math常用的数学函数
- Java中Math类常用方法总结 + Random类与Math类小结合
- java math常用函数
- java 常用Math类中的方法总结
- C#中Math类常用函数
- 【Math类】常用函数
- Java中Math类的常用方法
- Java中Math类的常用方法
- Java中Math类的常用方法
- Java中Math类的常用方法
- Java中Math类的常用方法
- 用js解决杨辉三角问题
- 第十一周总结
- 高精度计算(附高精度加法程序)
- 基本正则表达式个人总结(以CentOS 6.3环境下shell为例)
- POJ 1024 Tester Program 笔记
- Java中Math类常用函数总结
- 数据结构-循环队列的基本实现操作
- PowerDesigner、Rational Rose、Visio三种建模工具比较
- 一个程序员的爱情故事
- 请编写一个函数fun(char *s),其功能是:将s所指字符串中所有的字母改写成该字母的下一个字母,若是z字母,则改为a字母,大、小写保持不变。
- Centso可以访问外网但ping不通www.baidu.com
- 垃圾回收机制
- LEETCODE84Largest Rectangle in Histogram
- 【XML解析】使用Jaxp对XML进行DOM解析