IT박스

Java에서 무한대를 구현하는 방법은 무엇입니까?

itboxs 2020. 7. 7. 07:55
반응형

Java에서 무한대를 구현하는 방법은 무엇입니까?


Java에는 모든 숫자 데이터 유형에 대해 무한대를 나타내는 것이 있습니까? 수학 연산을 수행 할 수 있도록 어떻게 구현됩니까?

예 :

int myInf = infinity; //However it is done
myInf + 5; //returns infinity
myInf*(-1); //returns negative infinity

나는 매우 큰 숫자를 사용하려고 시도했지만 적절하고 쉬운 해결책을 원합니다 .


double 무한대 지원

double inf = Double.POSITIVE_INFINITY;
System.out.println(inf + 5);
System.out.println(inf - inf); // same as Double.NaN
System.out.println(inf * -1); // same as Double.NEGATIVE_INFINITY

인쇄물

Infinity
NaN
-Infinity

참고 : Infinity - Infinity숫자아닙니다 .


이유 때문에 정수 수학을 사용한다고 가정합니다. 그렇다면 Integer클래스 의 MAX_VALUE 필드를 사용하여 POSITIVE_INFINITY와 기능적으로 거의 동일한 결과를 얻을 수 있습니다 .

Integer myInf = Integer.MAX_VALUE;

(그리고 NEGATIVE_INFINITY의 경우 MIN_VALUE를 사용할 수 있습니다.) 물론 myInfMAX_VALUE에 해당하는 값 과 비교할 때 기능적인 차이 가있을 수 있습니다. 분명히이 숫자는보다 작지 않습니다 myInf.

이 또한의 도서관 실제로 필드 POSITIVE_INFINITY 및 NEGATIVE_INFINITY을 가지고 있지만, 그들은 정말 MAX_VALUE와 MIN_VALUE 단지의 새로운 이름입니다.


사용하려면 Infinity다음 Double을 지원 Infinity하십시오.-

    System.out.println(Double.POSITIVE_INFINITY);
    System.out.println(Double.POSITIVE_INFINITY * -1);
    System.out.println(Double.NEGATIVE_INFINITY);

    System.out.println(Double.POSITIVE_INFINITY - Double.NEGATIVE_INFINITY);
    System.out.println(Double.POSITIVE_INFINITY - Double.POSITIVE_INFINITY);

출력 :-

Infinity
-Infinity
-Infinity

Infinity 
NaN

DoubleFloat유형은이 POSITIVE_INFINITY상수.


Java가 모든 숫자 유형에 대해 무한대를 가지고 있는지 확실하지 않지만 일부 숫자 데이터 유형에 대한 대답은 긍정적입니다.

Float.POSITIVE_INFINITY
Float.NEGATIVE_INFINITY

또는

Double.POSITIVE_INFINITY
Double.NEGATIVE_INFINITY

또한 +/- 무한대와 관련된 수학적 연산을 나타내는 다음 기사를 유용하게 찾을 수 있습니다. Java 부동 소수점 수 복잡성 .


Double 및 Float 유형 만 POSITIVE_INFINITY상수를 지원 합니다.


숫자 래퍼 유형의 경우.

예 : Double.POSITVE_INFINITY

이것이 당신을 도울 수 있기를 바랍니다.


A generic solution is to introduce a new type. It may be more involved, but it has the advantage of working for any type that doesn't define its own infinity.

If T is a type for which lteq is defined, you can define InfiniteOr<T> with lteq something like this:

class InfiniteOr with type parameter T:
    field the_T of type null-or-an-actual-T
    isInfinite()
        return this.the_T == null
    getFinite():
        assert(!isInfinite());
        return this.the_T
    lteq(that)
        if that.isInfinite()
            return true
        if this.isInfinite()
            return false
        return this.getFinite().lteq(that.getFinite())

I'll leave it to you to translate this to exact Java syntax. I hope the ideas are clear; but let me spell them out anyways.

The idea is to create a new type which has all the same values as some already existing type, plus one special value which—as far as you can tell through public methods—acts exactly the way you want infinity to act, e.g. it's greater than anything else. I'm using null to represent infinity here, since that seems the most straightforward in Java.

If you want to add arithmetic operations, decide what they should do, then implement that. It's probably simplest if you handle the infinite cases first, then reuse the existing operations on finite values of the original type.

There might or might not be a general pattern to whether or not it's beneficial to adopt a convention of handling left-hand-side infinities before right-hand-side infinities or vice versa; I can't tell without trying it out, but for less-than-or-equal (lteq) I think it's simpler to look at right-hand-side infinity first. I note that lteq is not commutative, but add and mul are; maybe that is relevant.

Note: coming up with a good definition of what should happen on infinite values is not always easy. It is for comparison, addition and multiplication, but maybe not subtraction. Also, there is a distinction between infinite cardinal and ordinal numbers which you may want to pay attention to.


Since the class Number is not final, here is an idea, that I don't find yet in the other posts. Namely to subclass the class Number.

This would somehow deliver an object that can be treated as infinity for Integer, Long, Double, Float, BigInteger and BigDecimal.

Since there are only two values, we could use the singleton pattern:

public final class Infinity extends Number {
    public final static Infinity POSITIVE = new Infinity(false);
    public final static Infinity NEGATIVE = new Infinity(true);
    private boolean negative;
    private Infinity(boolean n) {
        negative = n;
    }
}

Somehow I think the remaining methods intValue(), longValue() etc.. should then be overriden to throw an exceptions. So that the infinity value cannot be used without further precautions.

참고URL : https://stackoverflow.com/questions/12952024/how-to-implement-infinity-in-java

반응형