1. 程式人生 > >03-java.lang.Math+java.util.Random+java.math.BigDecimal

03-java.lang.Math+java.util.Random+java.math.BigDecimal

一、java.lang.Math

1、概述

(1)public final class Math:不能被繼承,即沒有子類

(2)Math類包含用於執行基本數學運算的方法,其中的方法都是靜態的 -- 工具類

2、欄位

(1)static final double E:自然對數的底數

(2)static final double PI:圓周率

3、方法(返回值多為double)

(1)static double abs(Xxx a):a的絕對值。Xxx可以是int、long、float、double型別

(2)static double max(Xxx a, Xxx b):a、b中的較大值。Xxx可以是int、long、float、double型別

(3)static double min(Xxx  a, Xxx b):a、b中的較小值。Xxx可以是int、long、float、double型別

(4)static double ceil(double a):進1,為double型別的整數

(5)static double floor(double a):去尾,為double型別的整數

(6)static longround(double a):四捨五入取整long

(7)static int round(float a):四捨五入取整int

        double arg = 12.56;
        double a = Math.floor(arg);
        // int d = Math.round(arg);    //報錯,long-->int會有精度損失
        long b = Math.round(arg);
        double c = Math.ceil(arg);
        System.out.println(a);  //12.0
        System.out.println(b);  //13
        System.out.println(c);  //13.0

(8)static double random():偽隨機數,返回帶正號的double值,範圍為[0.0, 1.0)

        double a = Math.floor(Math.random() * 10); //[0.0, 9.0]
        double b = Math.ceil(Math.random() * 10);  //[1.0, 10.0]
        double c = (int) (Math.random() * 6 + 1);  //[1.0, 6.0],類似搖骰子

注:隨機數是沒有任何規律的,而偽隨機數當計算次數足夠多時,可以找到規律(偽隨機數在指定範圍內近似均勻分佈)

補充:java.util.Random類,也可獲取偽隨機數

(9)static double sqrt(double a):double值的正平方根

(10)static double pow(double a, double b):a的b次冪

(11)static double exp(double a):e的a次冪

(12)static double log(double a):double值的自然對數(底數是e)

(13)static double log10(double a):double值的底數為10的對數

二、java.util.Random

1、Random通常用作隨機數生成器

2、構造方法

(1)Random():使用當前時間作為種子 -- 常用

(2)Random(long seed):以一個固定值作為種子

說明:建構函式 Random() 中使用 this(xxx); 呼叫建構函式 Random(seed)

          呼叫 new Random(seed); 等效於 Random rnd = new Random();  rnd.setSeed(seed);

    public Random() {
        this(seedUniquifier() ^ System.nanoTime());
    }

    private static long seedUniquifier() {
        long var0;
        long var2;
        do {
            var0 = seedUniquifier.get();
            var2 = var0 * 181783497276652981L;
        } while(!seedUniquifier.compareAndSet(var0, var2));

        return var2;
    }

    public Random(long var1) {
        this.haveNextNextGaussian = false;
        if (this.getClass() == Random.class) {
            this.seed = new AtomicLong(initialScramble(var1));
        } else {
            this.seed = new AtomicLong();
            this.setSeed(var1);
        }

    }

3、方法

(1)protected int next(int bits):生成下一個偽隨機數。使用seed進行計算,其他nextXxx()方法都是呼叫next()方法

(2)int nextInt(int n):[0, n)之間的int值

(3)float nextFloat():[0.0, 1.0]之間的float值

(4)double nextDouble():[0.0, 1.0)之間的double值

(5)boolean nextBoolean():值為true或false

(6)int nextInt()

(7)long nextLong()

(8)void setSeed(long seed):使用單個long種子設定此隨機數生成器的種子

        System.out.println("Random 不含參構造方法:");
        for (int i = 0; i < 5; i++) {
            Random random = new Random();
            for (int j = 0; j < 8; j++) {
                System.out.print(" " + random.nextInt(100) + ", ");
            }
            System.out.println("");
        }

        /**
         Random 不含參構造方法:
         99,  45,  33,  23,  26,  23,  83,  12,
         17,  24,  91,  91,  77,  19,  2,  64,
         52,  60,  79,  26,  66,  27,  72,  30,
         0,  93,  33,  16,  74,  77,  82,  1,
         31,  48,  45,  61,  28,  41,  11,  14,
         */

        System.out.println("");

        /**
         Random 含參構造方法:
         17,  88,  93,  12,  51,  61,  36,  58,
         17,  88,  93,  12,  51,  61,  36,  58,
         17,  88,  93,  12,  51,  61,  36,  58,
         17,  88,  93,  12,  51,  61,  36,  58,
         17,  88,  93,  12,  51,  61,  36,  58,
         */

        System.out.println("Random 含參構造方法:");
        for (int i = 0; i < 5; i++) {
            Random random = new Random(50);
            for (int j = 0; j < 8; j++) {
                System.out.print(" " + random.nextInt(100) + ", ");
            }
            System.out.println("");
        }

說明:隨機數是種子經過計算生成的。無參的建構函式每次都使用當前時間作為種子,隨機性更強。而含參的建構函式其實是偽隨機,更有可預見性

三、生成隨機數的方法

1、Math類:static double random() -- 此方法使用時需要 (int) (Math.random() * 6 + 1)

2、Random類:int nextInt(int n) 、 double nextDouble() -- 此方法使用時需要用 (int) (new Random().nextDouble() * 6 + 1); 強轉

四、程式設計:獲取digit位驗證碼

    /**
     * 獲取驗證碼
     *
     * @param digit 驗證碼的位數
     * @return
     */
    public static String getVerificationCode(int digit) {
        StringBuffer sb = new StringBuffer();
        Random rnd = new Random();
        for (int i = 0; i < digit; i++) {
            sb.append(rnd.nextInt(10));
        }
        return sb.toString();
    }

五、java.math.BigDecimal

1、BigDecimal extends Number:不可變的、任意精度的有符號十進位制數。BigDecimal提供以下操作:算數、標度操作、舍入、比較、雜湊演算法和格式轉換

2、在需要精確的小數計算時,才使用BigDecimal。因為BigDecimal的效能比float和double差

3、每次進行運算後,都會產生一個新的物件,要記得儲存操作後的值

4、建構函式

(1)BigDecimal(Xxx xxx):將Xxx型別的引數轉換成BigDecimal型別。Xxx型別可以為:String、char[]、BigInteger、int、long、 double

注:儘量使用引數型別為String的建構函式

5、方法

(1)static BigDecimal valueOf(double val):將double轉換為BigDecimal(使用Double.toString(double)方法提供的double規範的字串表示形式)

注:valueOf()通常是將double/float轉化為BigDecimal的首選方法(還可以用BigDecimal的建構函式)

        BigDecimal b1 = new BigDecimal("1.34");
        BigDecimal b2 = BigDecimal.valueOf(1.34);

(2)int intValue():將BigDecimal轉換為int。此轉換會丟失關於BigDecimal值的總大小(返回32位低位位元組)和精度(丟棄小數部分)的資訊,並返回帶有相反符號的結果 -- 基本收縮轉換

(3)int intValueExact():將BigDecimal轉換為int,以檢查丟失的資訊。如果BigDecimal具有非零小數部分,或者超出int結果的可能範圍,則丟擲ArithmeticException

(4)BigDecimal add(BigDecimal augend):加法,返回(this + augend)

    /**
     * 加法add
     * @param value1
     * @param value2
     * @return
     */
    public static double add(double value1, double value2) {
        BigDecimal b1 = new BigDecimal(value1);
        BigDecimal b2 = new BigDecimal(value2);
        return b1.add(b2).doubleValue();
    }

(5)BigDecimal subtract(BigDecimal subtrahend):減法,返回(this - subtrahend)

(6)BigDecimal multiply(BigDecimal multiplicand):乘法,返回(this * multiplicand)

(7)BigDecimal divide(BigDecimal divisor):除法,返回(this / divisor)

(8)BigDecimal divideToIntegralValue(BigDecimal divisor):返回向下舍入所得商值(this / divisor)的整數部分

        BigDecimal b1 = new BigDecimal("101.9");
        BigDecimal b2 = new BigDecimal("3");
        //divideToIntegralValue():向下取整
        System.out.println(b1.divideToIntegralValue(b2));   //33.0
        BigDecimal b3 = new BigDecimal("102.1");
        System.out.println(b3.divideToIntegralValue(b2));   //34.0
        BigDecimal b4 = new BigDecimal("101.99");
        System.out.println(b4.divideToIntegralValue(b2));   //33.00

(9)BigDecimal remainder(BigDecimal divisor):取餘,返回(this % divisor)

        BigDecimal b1 = new BigDecimal("513.54");
        BigDecimal b2 = new BigDecimal("5");
        System.out.println(b1.remainder(b2));   //3.54

(10)BigDecimal[] divideAndRemainder(BigDecimal divisor):返回由兩個元素組成的BigDecimal陣列,商值(this / val)是初始元素,餘數(this % val)是最終元素。如果同時需要整數商和餘數,divideAndRemainder()比 divideToIntegralValue() + remainder() 更快速,因為相除僅需執行一次

        BigDecimal b1 = new BigDecimal("513.54");
        BigDecimal b2 = new BigDecimal("5");
        BigDecimal[] bigDecimals = b1.divideAndRemainder(b2);
        System.out.println(Arrays.deepToString(bigDecimals));   //[102.00, 3.54]

(11)BigDecimal movePointLeft(int n):等效於將該值的小數點向左移動n位。n為負數等效於movePointRight(-n)

(12)BigDecimal movePointRight(int n):等效於將該值的小數點向右移動n位。n為負數等效於movePointLeft(-n)

(13)BigDecimal negate():返回( - this )

        BigDecimal b1 = new BigDecimal("101.9");
        BigDecimal b2 = new BigDecimal("-101.9");
        System.out.println(b1.negate());   //-101.9"
        System.out.println(b2.negate());   //101.9

(14)BigDecimal plus():返回( + this )

        BigDecimal b1 = new BigDecimal("101.9");
        BigDecimal b2 = new BigDecimal("-101.9");
        System.out.println(b1.plus());   //101.9
        System.out.println(b2.plus());   //-101.9"

(15)BigDecimal pow(int n):返回this的n次方

(16)int compareTo(BigDecimal val):BigDecimal與指定的BigDecimal比較。值相等但具有不同標度的兩個BigDecimal物件被認為是相等的。當此BigDecimal在數字上小於、等於、大於val時,返回 -1、0、1

注:equals()比的是值是否相同

        BigDecimal b1 = new BigDecimal("1");
        BigDecimal b2 = new BigDecimal("2");
        BigDecimal b3 = new BigDecimal("1");

        System.out.println(b1.compareTo(b2));   //-1
        System.out.println(b1.compareTo(b3));   //0
        System.out.println(b2.compareTo(b1));   //1

        System.out.println(b1.equals(b2));  //false
        System.out.println(b1.equals(b3));  //true

(17)BigDecimal abs():絕對值

(18)BigDecimal max(BigDecimal val):BigDecimal和val的最大值

(19)BigDecimal min(BigDecimal val):BigDecimal和val的最小值

(20)int precision():返回BigDecimal的精度(精度是非標度值的數字個數,0值的精度是1)

(21)int scale():返回BigDecimal的標度。如果為0或正數,標度是小數點後的位數;如果為負數,則將該數的非標度值乘以10的負scale次冪

(22)BigInteger toBigInteger():將BigDecimal轉換為BigInteger。此轉換會丟失關於BigDecimal值的精度資訊

(23)BigInteger toBigIntegerExact():將BigDecimal轉換為BigInteger,以檢查丟失的資訊。如果BigDecimal具有非零小數部分,則丟擲ArithmeticException異常

(24)String toString():返回BigDecimal的字串表示形式,如果需要指數,則使用科學記數法

(25)String toEngineeringString():返回BigDecimal的字串表示形式,需要指數時,則使用工程記數法

(26)String toPlainString():返回不帶指數字段的BigDecimal的字串表示形式

6、練習

相關推薦

03-java.lang.Math+java.util.Random+java.math.BigDecimal

一、java.lang.Math 1、概述 (1)public final class Math:不能被繼承,即沒有子類 (2)Math類包含用於執行基本數學運算的方法,其中的方法都是靜態的 -- 工具類 2、欄位 (1)static final double E:

java lang(Comparable接口) 和java util(Comparator接口)分析比較

比較 inter add 自動 bject ret 動態 clas ons //Comparable 接口強行對實現它的每個類的對象進行整體排序。 -- 自然排序。類的compareTo稱為自然比較方法。 public interface Comparable<T

java.lang.NoSuchMethodError:....Ljava/util/List;

Caused by: java.lang.NoSuchMethodError: com.liyapuinfo.hzz.api.MdLocusrecordApi.findMyPatrol(Ljava/lang/Integer;)Ljava/util/List;     

java異常 java.lang.ClassNotFoundException: javassist.util.proxy.MethodFilter

java.lang.ClassNotFoundException: javassist.util.proxy.MethodFilter異常主要是因為缺少javassist包導致的 Javassist是一個開源的分析、編輯和建立Java位元組碼的類庫。它允許開發者自由的在一個

java.lang.SecurityException: Prohibited package name: java.util 問題分享

有一個需求需要將spring加入到非maven的工程中,手動一個個的加包是不可避免的,然後spring載入要要自己做也是必須的,我首次使用的是jdk1.8,用的是spring 4.3.9,版本,在我的機器上執行的時分良好, String fileName=Constants

Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'xxx'

今天在完成專案的時候遇到了下面的異常資訊: 04-Aug-2014 15:49:27.894 SEVERE [http-apr-8080-exec-5] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for se

Exception in thread "main" java.lang.UnsatisfiedLinkError: no awt in java.library.path: [

點擊 exception exceptio 本地 thread 圖片 lib reference 解決 Exception in thread "main" java.lang.UnsatisfiedLinkError: no awt in java.l

java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path

java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path thrown while loading gnu.io.RXTXCommDriver Exception in thread "main" java.lang.Uns

HibernateProxy異常處理 java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class:

這裡使用google的Gson包做JSON轉換,因為較早的1.4版本的FieldAttributes類中沒有getDeclaringClass()這個方法,這個方法是獲取field所屬的類,在我的排除策略中會用到。 排除策略    最簡單的gson轉換可以是這樣的,但卻

java.lang.SecurityException: Prohibited package name:java.xxx.xxx.xxx

java.lang.SecurityException: Prohibited package name: java.xxx.yyy.zzz java.patterns.v1.Test java.lang.SecurityException: Prohibited package nam

java.lang.UnsatisfiedLinkError: no XXX in java.library.path

1、 在載入jni類之前 放入“System.out.println( System.getProperty("java.library.path")); 2、執行程式將獲得java.library.path指向的目錄 3、拷貝libxxx.so 或xxx.dll到java

Weblogic 部署問題:java.lang.UnsatisfiedLinkError: no orii in java.library.path

專案需要Weblogic部署,但是重啟Weblogic發現報這個問題,網上找了半天沒找到解決問題,突然腦子一抽筋,怎麼用root賬戶啟動了,錯誤如下: ​ java.lang.UnsatisfiedLinkError: no orii in java.library.pat

BUG(3) : Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer';

Failed to bind request element: org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of

java.lang.Thread.sleep()方法和java.lang.Object.wait()方法之間的區別

java.lang.Thread.sleep(): sleep()方法為Thread類定義的靜態方法,因此需要通過Thread類呼叫該方法: Thread.sleep(1000); Javadoc對該方法的描述如下: Causes the currently executi

[JAVA] 日常填坑 java.lang.SecurityException: Prohibited package name: java.xxx

package java.patterns.v1; import capsule.patterns.v1.factory.SendFactory; public class Test {

idea 配置opencv新增opencv庫了還報錯java.lang.UnsatisfiedLinkError: no opencv_java342 in java.library.path

開啟“Run/Debug Configurations"對話方塊 在VM options裡新增: -Djava.library.path=E:\\opencv\\opencv\\build\\java\\x64

invalid comparison: java.util.ArrayList and java.lang.String——bug解決辦法

幫助 lang iso 數據 null array size for close 今天碰到個問題,解決了很久才搞定,來記錄下,希望可以幫助到大家 貼錯誤源碼: 這是一個根據list集合的查找數據的 sql,在接收list的時候加了判斷 list != ‘ ’ “”,引起了集

170616、解決 java.lang.IllegalArgumentException: No converter found for return value of type: class java.util.ArrayList

pen group string image exception bean val 轉換 技術 報錯截圖: 原因:搭建項目的時候,springmvc默認是沒有對象轉換成json的轉換器的,需要手動添加jackson依賴。 解決步驟: 1、添加jackson依賴到pom

Maven項目Eclipse啟動時報錯: java.lang.ClassNotFoundException: org.springframework.web.util.IntrospectorCleanupListener

otf exce exe maven com apply ges 選中項 apache Eclipse中啟動Maven項目時報如下錯誤: 嚴重: Error configuring application listener of class org.springfra

解決java.lang.IllegalArgumentException: No converter found for return value of type: class java.util.ArrayList這個問題

method posit adapt orm ask resp 運行 poi erro 今天使用SSM框架,用@ResponseBody註解,出現了這個問題 java.lang.IllegalArgumentException: No converter found f