Programing

Java의 부동 및 이중 데이터 유형

lottogame 2020. 4. 30. 07:27
반응형

Java의 부동 및 이중 데이터 유형


float 데이터 형식은 단 정밀도 32 비트 IEEE 754 부동 소수점이고 double 데이터 형식은 배정 밀도 64 비트 IEEE 754 부동 소수점입니다.

무슨 뜻이에요? 그리고 언제 double 대신 float를 사용해야합니까?


위키 페이지 그것에는 시작하기에 좋은 장소입니다.

요약하면 :

  • float는 1 비트 비트, 8 비트 지수 및 23 비트의 부호와 함께 32 비트로 표시됩니다 (또는 과학적 표기법 번호 : 2.33728 * 10 12 ; 33728은 부호입니다).

  • double 는 1 비트 비트, 11 비트 지수 및 52 비트의 부호와 함께 64 비트로 표시됩니다.

기본적으로 Java는 double부동 소수점 숫자를 나타내는 데 사용 합니다 (따라서 리터럴 3.14은 유형이 지정됨 double). 또한 훨씬 더 큰 숫자 범위를 제공하는 데이터 유형이므로을 (를) 사용하는 것이 좋습니다 float.

특정 실제로 당신의 사용을 강제 라이브러리가있을 수 float있지만, 일반적으로 - 당신은 당신의 결과에 맞게 충분히 작은 될 것이라고 보장 할 수없는 float'의 규정 범위를 , 그것은으로 선택하는 것이 좋습니다 double.

당신은 정확성이 필요한 경우 - 예를 들어, 당신은 (같은 부정확 진수 값을 가질 수 없습니다 1/10 + 2/10), 또는 당신이하고있는 어떤 (시스템에 $ 10.33를 나타내는 예를 들어,) 통화와, 다음을 사용 BigDecimal를 지원할 수있는을, 임의의 정밀도와 그런 상황을 우아하게 처리합니다.


플로트는 대략 당신에게 준다. 6 자리-10 진수는 정밀도가 두 배이지만 15-16. 또한 숫자의 범위는 두 배로 큽니다.

double은 8 바이트의 저장 공간이 필요하지만 float는 4 바이트 만 필요합니다.


실수로도 알려진 부동 소수점 숫자는 분수 정밀도가 필요한 표현식을 평가할 때 사용됩니다. 예를 들어, 제곱근과 같은 계산 또는 사인 및 코사인과 같은 초월 계산은 정밀도에 부동 소수점 유형이 필요한 값이됩니다. Java는 표준 (IEEE–754) 부동 소수점 유형 및 연산자 세트를 구현합니다. 부동 소수점 유형에는 float 및 double의 두 종류가 있으며, 각각 단 정밀도 및 배정 밀도 숫자를 나타냅니다. 너비와 범위는 다음과 같습니다.


   Name     Width in Bits   Range 
    double  64              1 .7e–308 to 1.7e+308
    float   32              3 .4e–038 to 3.4e+038


흙손

float 유형은 32 비트 스토리지를 사용하는 단 정밀도 값을 지정합니다. 단 정밀도는 일부 프로세서에서 더 빠르며 배정 밀도의 절반만큼 공간을 차지하지만 값이 매우 크거나 작 으면 정확하지 않습니다. float 유형의 변수는 분수 구성 요소가 필요할 때 유용하지만 큰 정밀도를 요구하지는 않습니다.

float 변수 선언의 예는 다음과 같습니다.

부유물 고온, 저온;


더블

double 키워드로 표시되는 배정 밀도는 64 비트를 사용하여 값을 저장합니다. 고속 수학적 계산에 최적화 된 일부 최신 프로세서에서는 실제로 배정도가 단 정도보다 빠릅니다. sin (), cos () 및 sqrt ()와 같은 모든 초월 수학 함수는 double 값을 반환합니다. 많은 반복 계산에서 정확도를 유지해야하거나 값이 큰 숫자를 조작하는 경우 double이 가장 좋습니다.


그럼에도 불구하고 Java는 계산에 double을 사용하는 것에 대한 편견이있는 것 같습니다.

필자가 오늘 일찍 작성한 프로그램에서 float을 사용할 때 메소드가 작동하지 않지만 float을 double로 대체하면 훌륭하게 작동합니다 (NetBeans IDE에서).

package palettedos;
import java.util.*;

class Palettedos{
    private static Scanner Z = new Scanner(System.in);
    public static final double pi = 3.142;

    public static void main(String[]args){
        Palettedos A = new Palettedos();
        System.out.println("Enter the base and height of the triangle respectively");
        int base = Z.nextInt();
        int height = Z.nextInt();
        System.out.println("Enter the radius of the circle");
        int radius = Z.nextInt();
        System.out.println("Enter the length of the square");
        long length = Z.nextInt();
        double tArea = A.calculateArea(base, height);
        double cArea = A.calculateArea(radius);
        long sqArea = A.calculateArea(length);
        System.out.println("The area of the triangle is\t" + tArea);
        System.out.println("The area of the circle is\t" + cArea);
        System.out.println("The area of the square is\t" + sqArea);
    }

    double calculateArea(int base, int height){
        double triArea = 0.5*base*height;
        return triArea;
    }

    double calculateArea(int radius){
        double circArea = pi*radius*radius;
        return circArea;
    }

    long calculateArea(long length){
        long squaArea = length*length;
        return squaArea;
    }
}

IEEE 표준에 따르면 float는 실수의 32 비트 표현이고 double은 64 비트 표현입니다.

In Java programs we normally mostly see the use of double data type. It's just to avoid overflows as the range of numbers that can be accommodated using the double data type is more that the range when float is used.

Also when high precision is required, the use of double is encouraged. Few library methods that were implemented a long time ago still requires the use of float data type as a must (that is only because it was implemented using float, nothing else!).

But if you are certain that your program requires small numbers and an overflow won't occur with your use of float, then the use of float will largely improve your space complexity as floats require half the memory as required by double.


This example illustrates how to extract the sign (the leftmost bit), exponent (the 8 following bits) and mantissa (the 23 rightmost bits) from a float in Java.

int bits = Float.floatToIntBits(-0.005f);
int sign = bits >>> 31;
int exp = (bits >>> 23 & ((1 << 8) - 1)) - ((1 << 7) - 1);
int mantissa = bits & ((1 << 23) - 1);
System.out.println(sign + " " + exp + " " + mantissa + " " +
  Float.intBitsToFloat((sign << 31) | (exp + ((1 << 7) - 1)) << 23 | mantissa));

The same approach can be used for double’s (11 bit exponent and 52 bit mantissa).

long bits = Double.doubleToLongBits(-0.005);
long sign = bits >>> 63;
long exp = (bits >>> 52 & ((1 << 11) - 1)) - ((1 << 10) - 1);
long mantissa = bits & ((1L << 52) - 1);
System.out.println(sign + " " + exp + " " + mantissa + " " +
  Double.longBitsToDouble((sign << 63) | (exp + ((1 << 10) - 1)) << 52 | mantissa));

Credit: http://s-j.github.io/java-float/


This will give error:

public class MyClass {
    public static void main(String args[]) {
        float a = 0.5;
    }
}

/MyClass.java:3: error: incompatible types: possible lossy conversion from double to float float a = 0.5;

This will work perfectly fine

public class MyClass {
    public static void main(String args[]) {
        double a = 0.5;
    }
}

This will also work perfectly fine

public class MyClass {
    public static void main(String args[]) {
        float a = (float)0.5;
    }
}

Reason : Java by default stores real numbers as double to ensure higher precision.

Double takes more space but more precise during computation and float takes less space but less precise.

참고URL : https://stackoverflow.com/questions/27598078/float-and-double-datatype-in-java

반응형