précédent | suivant | table des matières s'évaluer

BigInteger et BigDecimal

Sommaire
  1. BigInteger
    1. Constructeurs
    2. Opérations habituelles
    3. Nombres premiers
    4. Arithmétique modulaire
    5. Divers
  2. BigDecimal
    1. RoundingMode
    2. MathContext
    3. Constructeurs
    4. Opérations habituelles
    5. Divers

Les classes BigInteger et BigDecimal permettent de représenter des entiers ou des nombres flottants sans les limitations de taille des types primtifs entiers, flottants ou des enveloppes des types primitifs. La classe BigInteger offre en plus des opérations habituelles sur les entiers, des opérations de calcul en arithmétique modulaire, calcul du pgcd, génération de nombre premier, test pour savoir si un entier est premier, etc...
La classe BigDecimal permet de travailler avec des nombres décimaux, en précisant le nombre de chiffres significatifs, et le mode d'arrondi utilisé lors des opérations sur les BigDecimal.
Les classes BigInteger et BigDecimal sont immuables.

1 BigInteger.

Un objet de la classe BigInteger est représenté avec deux attributs : le signe et un tabeau de int représentant les chiffres de l'entier en base 2L×Integer.MAX_VALUE+1 (4294967295).

La classe BigInteger contient 3 constantes :

   ZERO
   ONE
   TEN

1.1 Constructeurs.

BigInteger(byte[] val)
Construit un BigInteger à partir de sa représentation en complément à 2 contenue dans le tableau val. Les bits de plus fort poids sont rangés dans val[0]
exemple:
byte [] v = {0,-1};
byte [] v1 = {-1};
BigInteger d = new BigInteger(v);
BigInteger d1 = new BigInteger(v1)
d vaut -1 et d1 vaut 255.
BigInteger(int signe, byte[] val)
Le signe est 1 pour +, -1 pour - et 0 pour 0 (dans ce cas val doit contenir 0).
exemple:
byte [] v = {-1};
BigInteger d = new BigInteger(1, v);
d vaut 255.
BigInteger(int bitLong, 
           int certainty, Random rnd)
Construit un BigInteger positif qui est probablement premier, avec une représentation en binaire de longueur bitLong. La probabilité que l'entier soit premier dépasse 1-1/2certainty. Le temps de construction de l'entier est proportionnel à certainty.
BigInteger(int nbBits, Random rnd)
Construit un BigInteger de valeur aléatoire sur l'intervalle [0, 2nbBits-1]
BigInteger(String s)
Construit un BigInteger à partir de sa représentation en base 10 dans la chaîne de caractères s.
BigInteger(String s, int base)
Construit un BigInteger à partir de sa représentation en base basedans la chaîne de caractères s.

1.2 Opérations habituelles.

Les opérations sont celles des types primitifs +, -, *, /, %, ~, &, ^, |, >> (mais pas >>> !), <<, <, <=, >, >= et ==.

BigInteger add( BigInteger v)
Retourne this + v
BigInteger subtract( BigInteger v)
Retourne this - v
BigInteger multiply( BigInteger v)
Retourne this * v
L'algorithme utilisé est l'algorithme de l'école, bien qu'on connaisse des algorithmes plus rapides. Voir ici.
BigInteger divide( BigInteger v)
Retourne this / v
BigInteger remainder( BigInteger v)
Retourne this % v
BigInteger[] divideAndRemainder( BigInteger v)
Retourne un tableau de deux BigInteger qui sont le quotient et le reste de la division de this et v
BigInteger not( )
Retourne ~ this
BigInteger and( BigInteger v)
Retourne this & v
BigInteger andNot( BigInteger v)
Retourne this & ~ v
BigInteger xor( BigInteger v)
Retourne this ^ v
BigInteger or( BigInteger v)
Retourne this | v
BigInteger shiftLeft(int n)
Retourne this << n
BigInteger shiftRight(int n)
Retourne this >> n
BigInteger equals( object v)
Retourne this == v
BigInteger compareTo( BigInteger v)
Retourne
  -1 si this < v
   0 si this == v
  +1 si this > v

1.3 BigInteger et les nombres premiers.

Les méthodes permettant de travailler avec des nombres premiers ou en arithmétique modulaire sont très utilisées en cryptographie.

static BigInteger probablePrime(int bitLong,
                                Random rnd)
Retourne un BigInteger construit par BigInteger(bitLong, 100, rnd);
static BigInteger nextProbablePrime()
Retourne le premier BigInteger plus grand que this qui est probablement un nombre premier. La probabilité que ce BigInteger ne soit pas un nombre premier est inférieure à 2-100. Le temps d'exécution est proportionnel à certainty.
boolean isProbablePrime(int certainty)
Retourne true si le BigInteger est probablement un nombre premier, et false sinon. Deux tests sont utilisés : le test de Miller-Rabin et le test de Lucas-Lehmer. La probabilité que ce BigInteger ne soit pas un nombre premier est inférieure à 2-certainty.

1.4 Arithmétique modulaire.

Quelques méthodes permettent de faire de l'arithmétique modulaire et sont utiles en cryptographie.

BigInteger mod(BigInteger m)
Retourne le reste de la division de this par m. this doit être strictement positif.
BigInteger modInverse(BigInteger m)
Retourne this -1 mod m. this doit être strictement positif.
BigInteger modPow(BigInteger p, BigInteger m)
Retourne this p mod m. this doit être strictement positif.

1.5 Diverses méthodes.

BigInteger gcd(BigInteger b)
Retourne le PGCD de this et b.
BigInteger pow(int p)
Retourne this p.
BigInteger abs()
Retourne |this|.
BigInteger negate()
Retourne -this.
BigInteger min(BigInteger b)
BigInteger max(BigInteger b)
BigInteger setBit(int n)
Retourne this | (1<<n).
BigInteger clearBit(int n)
Retourne this & ~(1<<n).
BigInteger flipBit(int n)
Retourne this ^ (1<<n).
int testBit(int n)
Retourne true si le nième bit est à 1 et false sinon.
boolean getLowestSetBit()
Retourne le rang du bit le plus à droite qui vaut 1.

2 BigDecimal.

La classe BigDecimal permet de représenter des nombres décimaux en spécifiant le nombre de chiffres significatifs, et le mode d'arrondi utilisé lors des opérations.

Une instance de BigDecimal est représentée par trois attributs :

  1. intVal : un BigInteger représentant les chiffres du BigDecimal
  2. scale : un int représentant la position de la virgule dans la suite de chiffres de intVal. Le BigDecimal est égal à intVal×10 -scale.
  3. precision : un int représentant le nombre de chiffres utilisés pour représenter le BigDecimal.

On se rendra compte de l'utilité des BigDecimal en testant les deux séquences suivantes. En théorie x vaut toujours 1 dans l'itération !

 MathContext mc = new MathContext(5, 
                      RoundingMode.HALF_UP);
 BigDecimal b = new BigDecimal(4095.1);
 BigDecimal a = b.add(new BigDecimal(1));
 BigDecimal x = new BigDecimal(1);
		  
 for (int i = 1; i < 10; i++) {
    x = x.multiply(a, mc).subtract(b, mc);
    System.out.println(i+" -> "+x);
 }
 double b = 4095.1;
 double a = b+1;
 double x = 1;
		  
 for (int i = 1; i < 10; i++) {
    x = x*a-b;
    System.out.println(i+" -> "+x);
 }

2.1 RoundingMode.

L'énumération RoundingMode permet d'énumérer les différent types d'arrondi utilisés par BigDecimal

Exemples
Nombre UP DOWN CEILING FLOOR HALF_UP HALF_DOWN HALF_EVEN UNNECESSARY
5.5 6 5 6 5 6 5 6
throw ArithmeticException
2.5 3 2 3 2 3 2 2
throw ArithmeticException
1.6 2 1 2 1 2 2 2
throw ArithmeticException
1.1 2 1 2 1 1 1 1
throw ArithmeticException
1.0 1 1 1 1 1 1 1
1
-1.0 -1 -1 -1 -1 -1 -1 -1
-1
-1.1 -2 -1 -1 -2 -1 -1 -1
throw ArithmeticException
-1.6 -2 -1 -1 -2 -2 -2 -2
throw ArithmeticException
-2.5 -3 -2 -2 -3 -3 -2 -2
throw ArithmeticException
-5.5 -6 -5 -5 -6 -6 -5 -6
throw ArithmeticException

2.2 MathContext.

La classe MathContext permet de spécifier une précision et un mode d'arrondi pour les opérations qui le nécessitent.

MathContext (int precision)
Construit un MathContext avec une précision precision et le mode d'arrondi par défaut (HALF_UP).
MathContext (int precision,
             RoundinMode rm)
Construit un MathContext avec une précision precision et le mode d'arrondi rm.
MathContext (String s)
s contient une chaîne de caractères obtenue par le toString de MathContext, et on construit un MathContext équivalent.

2.3 Constructeurs.

BigDecimal(double val) 
Construit un BigDecimal à partir d'un double. val ne peut être ni infinity ni NaN, sinon il y a une levée d'exception.
BigDecimal(double val, MathContext mc)
Construit un BigDecimal à partir d'un double et de mc. val ne peut être ni infinity ni NaN, sinon il y a une levée d'exception.
BigDecimal(BigInteger val)
BigDecimal(BigInteger val, int scale)
On indique le nombre de chiffres de la partie décimale avec le paramètre scale.
BigDecimal(BigInteger val, int scale,
           MathContext mc)
BigDecimal(BigInteger val,
           MathContext mc)
BigDecimal(int val)
BigDecimal(int val, MathContext mc)
BigDecimal(long val)
BigDecimal(long val, MathContext mc)
BigDecimal(String s)
Construit un BigDecimal à partir de sa représentation sous forme de chaîne de caractères.
new BigDecimal("314159e-5")
construit le BigDecimal de valeur 3.14159
BigDecimal(String s, MathContext mc)
BigDecimal(char[] s)
Construit un BigDecimal à partir de sa représentation sous forme de tableau de caractères.
char[] t = {'3', '.', '1', '4'};
new BigDecimal(t)
construit le BigDecimal de valeur 3.14
BigDecimal(char[] s, MathContext mc)

2.4 Opérations habituelles.

BigDecimal add(BigDecimal val) 
Retourne un BigDecimal égal à this + val. Le scale de la somme est le maximum des scale de this et val.
BigDecimal add(BigDecimal val, MathContext mc) 
Retourne un BigDecimal égal à this + val. mc peut modifier le nombre de chiffres significatifs, ou le mode d'arrondi.
BigDecimal subtract(BigDecimal val) 
Retourne un BigDecimal égal à this - val. Le scale de la soustraction est le maximum des scale de this et val.
BigDecimal subtract(BigDecimal val, MathContext mc) 
Retourne un BigDecimal égal à this - val. mc peut modifier le nombre de chiffres significatifs, ou le mode d'arrondi.
BigDecimal multiply(BigDecimal val) 
Retourne un BigDecimal égal à this * val. Le scale du produit est la somme des scale de this et val.
BigDecimal multiply(BigDecimal val, MathContext mc) 
Retourne un BigDecimal égal à this * val. Le scale du produit est la somme des scale de this et val. mc peut modifier le nombre de chiffres significatifs, ou le mode d'arrondi.
BigDecimal divide(BigDecimal val) 
Retourne un BigDecimal égal à this / val. Le scale du quotient est la différence des scale de this et val. Si on ne trouve pas un quotient exact une ArithmeticException est levée.
BigDecimal divide(BigDecimal val, MathContext mc) 
Retourne un BigDecimal égal à this / val. La division s'arrête lorsque le nombre de chiffres significatifs spécifiés par mc est atteint, ou lorsqu'un quotient exact est trouvé. mc peut modifier le mode d'arrondi.
BigDecimal divide(BigDecimal val, RoundingMode rm ) 
Retourne un BigDecimal égal à this / val. Le scale du quotient est le scale de this ou moins si le quotient est exact. Une exception est levée si rm vaut RoundingMode.UNNECESSARY.
BigDecimal[] divideAndRemainder(BigDecimal diviseur)
Retourne un tableau de 2 BigDecimal : l'un est le résultat de divideToIntegralValue, l'autre le reste avec un scale égal au scale de diviseur.
BigDecimal[] divideAndRemainder(BigDecimal diviseur,
                                MathContext mc)
Retourne un tableau de 2 BigDecimal : l'un est le résultat de divideToIntegralValue, l'autre le reste avec un scale égal au scale de diviseur.
BigDecimal[] divideToIntegralValue(BigDecimal diviseur)
Retourne un BigDecimal partie entière de la division de this par diviseur, avec un arrondi DOWN. Une exception est levée si mc.precision est plus petit que le nombre de chiffres de la partie entière.
BigDecimal[] divideToIntegralValue(BigDecimal diviseur,
                               MathContext mc)
Retourne un BigDecimal partie entière de la division de this par diviseur, avec un arrondi DOWN.
BigDecimal remainder(BigDecimal val) 
Retourne un BigDecimal égal à this - divideToIntegrelValue(val).multiply(val).
BigDecimal remainder(BigDecimal val, MathContext mc) 
Retourne un BigDecimal égal à this - divideToIntegrelValue(val).multiply(val). Si le quotient entier ne peut pas être calculé avec la précisioon de mc, il y a une levée d'exception.

2.5 Divers.

String toString() 
Retourne une chaîne de cractères représentant le BigDecimal. Suivant sa valeur, le BigDecimal est en notation scientifique si l'exposant est inférieur ou égal à -7, ou en notation décimale.
String toPlainString() 
Retourne une chaîne de caractères représentant le BigDecimal quelle que soit sa valeur.
String toEngineeringString() 
Retourne une chaîne de cractères représentant le BigDecimal. Suivant sa valeur, le BigDecimal est en notation scientifique si l'exposant est inférieur ou égal à -7, ou en notation décimale. L'exposant est dans ce cas toujours un multiple de 3.
BigDecimal pow(int p)
Retourne this p. Lève une exception si p est négatif. ZERO.pow(0) retourne 1. Les calculs se font sans limite sur la précision.
BigDecimal pow(int p, MathContext mc)
Retourne this p. Lève une exception si p est négatif. Les calculs se font avec la précision et l'arrondi de mc.
boolean equals(Object o)
Retourne true si o est un BigDecimal de même valeur, et false sinon. Pour qu'il y ait égalité, il faut que les valeurs et les scale soient identiques !
int compareTo(BigDecimal b)
Retourne 1 si this > b, 0 si this == b et -1 si this < b
BigDecimal negate()
BigDecimal negate(MathContext mc)
Retourne -this. La précision et le mode d'arrondi sont précisés par mc.
BigDecimal abs()
BigDecimal abs(MathContext mc)
Retourne |this|.La précision et le mode d'arrondi sont précisés par mc.
BigDecimal max(BigDecimal b)
Retourne le maximum des deux BigDecimal.
BigDecimal min(BigDecimal b)
Retourne le maximum des deux BigDecimal.
BigDecimal movePointLeft(int n)
Retourne this × 10 -n.
BigDecimal movePointRight(int n)
Retourne this × 10 n.
int scale()
Retourne le scale du BigDecimal.
BigDecimal setScale(int n)
BigDecimal setScale(int n, RoundingMode rm)
Retourne un BigDecimal de même valeur que this avec un scale de n. Si n est plus grand que scale le BigDecimal est étendu avec des 0 ; si n est plus petit que scale un RoundingMode doit être spécifié.
BigDecimal stripTrailingZeros()
Retourne un BigDecimal de même valeur que this en supprimant les zéros de fin après la virgule.

haut de la page