How to implement infinity in Java? - java

Does Java have anything to represent infinity for every numerical data type? How is it implemented such that I can do mathematical operations with it?
E.g.
int myInf = infinity; //However it is done
myInf + 5; //returns infinity
myInf*(-1); //returns negative infinity
I have tried using very large numbers, but I want a proper, easy solution.

double supports Infinity
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
prints
Infinity
NaN
-Infinity
note: Infinity - Infinity is Not A Number.

I'm supposing you're using integer math for a reason. If so, you can get a result that's functionally nearly the same as POSITIVE_INFINITY by using the MAX_VALUE field of the Integer class:
Integer myInf = Integer.MAX_VALUE;
(And for NEGATIVE_INFINITY you could use MIN_VALUE.) There will of course be some functional differences, e.g., when comparing myInf to a value that happens to be MAX_VALUE: clearly this number isn't less than myInf. Also, as noted in the comments below, incrementing positive infinity will wrap you back around to negative numbers (and decrementing negative infinity will wrap you back to positive).
There's also a library that actually has fields POSITIVE_INFINITY and NEGATIVE_INFINITY, but they are really just new names for MAX_VALUE and MIN_VALUE.

To use Infinity, you can use Double which supports 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);
OUTPUT: -
Infinity
-Infinity
-Infinity
Infinity
NaN

The Double and Float types have the POSITIVE_INFINITY constant.

Integer Infinity :
Integer maxNumber = Integer.MAX_VALUE
Double Infinity
Double maxNumber = Double.MAX_VALUE;
Double positiveInf = Double.POSITIVE_INFINITY;
Double negativeInf = Double.NEGATIVE_INFINITY
Float infinity
Float positiveInf = Float.POSITIVE_INFINITY;
Float negativeInf = Float.NEGATIVE_INFINITY
Float maxNumber = Float.MAX_VALUE;

I'm not sure that Java has infinity for every numerical type but for some numerical data types the answer is positive:
Float.POSITIVE_INFINITY
Float.NEGATIVE_INFINITY
or
Double.POSITIVE_INFINITY
Double.NEGATIVE_INFINITY
Also you may find useful the following article which represents some mathematical operations involving +/- infinity: Java Floating-Point Number Intricacies.

Only Double and Float type support POSITIVE_INFINITY constant.

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.

For the numeric wrapper types.
e.g Double.POSITIVE_INFINITY
Hope this might help you.

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.

I'm a beginner in Java...
I found another implementation for the infinity in the Java documentation, for the boolean and double types.
https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3
Positive zero and negative zero compare equal; thus the result of the
expression 0.0==-0.0 is true and the result of 0.0>-0.0 is false. But
other operations can distinguish positive and negative zero; for
example, 1.0/0.0 has the value positive infinity, while the value of
1.0/-0.0 is negative infinity.
It looks ugly, but it works.
public class Main {
public static void main(String[] args) {
System.out.println(1.0/0.0);
System.out.println(-1.0/0.0);
}
}

Related

How to get the int value from a floating point number?

If I am getting a random double, how to get only the int?
Examples:
1) 114.999 - get the "114" as an int
2) 565.343234 - get the "565" as an int.
Given the value :
float f = 114.999f;
int i = (int) f;
use a cast to downcast it to an int.
The simplest way would be to cast your double value to an int. For example,
(int) 114.9999 == 114
However, the double type can represent numbers beyond the range of an int. You may need to check if your double is below the smallest possible integer or beyond the largest possible integer to avoid integer overflow issues.
The easiest way to get the integer part of a floating point number would be a simple cast:
double d = 14.999;
int i = (int)d; //14
If you have a primitive wrapper like Double you can use the method intValue() that all subclasses of Number need to provide. However, since those are objects the references can be null and that has to be handled:
Double d = 14.999; //this makes use of auto-boxing
int i = d != null ? d.intValue() : 0; //here 0 is the default value if d is null
Note that this will just truncate the value which can lead to unexpected results due to precision issues, especially when calculations are involved. Due to that you could end up with a number like 14.999999999 when you'd expect 15 or something higher.
Another issue might be that you won't get the next smaller integer for negative values but the next higher, i.e. -14.999 will be truncated to -14.
You should keep that in mind and if those are issues for you have a look at the functions provided by the classes Math, BigDecimal etc.

Infinity in double primitive [duplicate]

Does Java have anything to represent infinity for every numerical data type? How is it implemented such that I can do mathematical operations with it?
E.g.
int myInf = infinity; //However it is done
myInf + 5; //returns infinity
myInf*(-1); //returns negative infinity
I have tried using very large numbers, but I want a proper, easy solution.
double supports Infinity
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
prints
Infinity
NaN
-Infinity
note: Infinity - Infinity is Not A Number.
I'm supposing you're using integer math for a reason. If so, you can get a result that's functionally nearly the same as POSITIVE_INFINITY by using the MAX_VALUE field of the Integer class:
Integer myInf = Integer.MAX_VALUE;
(And for NEGATIVE_INFINITY you could use MIN_VALUE.) There will of course be some functional differences, e.g., when comparing myInf to a value that happens to be MAX_VALUE: clearly this number isn't less than myInf. Also, as noted in the comments below, incrementing positive infinity will wrap you back around to negative numbers (and decrementing negative infinity will wrap you back to positive).
There's also a library that actually has fields POSITIVE_INFINITY and NEGATIVE_INFINITY, but they are really just new names for MAX_VALUE and MIN_VALUE.
To use Infinity, you can use Double which supports 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);
OUTPUT: -
Infinity
-Infinity
-Infinity
Infinity
NaN
The Double and Float types have the POSITIVE_INFINITY constant.
Integer Infinity :
Integer maxNumber = Integer.MAX_VALUE
Double Infinity
Double maxNumber = Double.MAX_VALUE;
Double positiveInf = Double.POSITIVE_INFINITY;
Double negativeInf = Double.NEGATIVE_INFINITY
Float infinity
Float positiveInf = Float.POSITIVE_INFINITY;
Float negativeInf = Float.NEGATIVE_INFINITY
Float maxNumber = Float.MAX_VALUE;
I'm not sure that Java has infinity for every numerical type but for some numerical data types the answer is positive:
Float.POSITIVE_INFINITY
Float.NEGATIVE_INFINITY
or
Double.POSITIVE_INFINITY
Double.NEGATIVE_INFINITY
Also you may find useful the following article which represents some mathematical operations involving +/- infinity: Java Floating-Point Number Intricacies.
Only Double and Float type support POSITIVE_INFINITY constant.
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.
For the numeric wrapper types.
e.g Double.POSITIVE_INFINITY
Hope this might help you.
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.
I'm a beginner in Java...
I found another implementation for the infinity in the Java documentation, for the boolean and double types.
https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3
Positive zero and negative zero compare equal; thus the result of the
expression 0.0==-0.0 is true and the result of 0.0>-0.0 is false. But
other operations can distinguish positive and negative zero; for
example, 1.0/0.0 has the value positive infinity, while the value of
1.0/-0.0 is negative infinity.
It looks ugly, but it works.
public class Main {
public static void main(String[] args) {
System.out.println(1.0/0.0);
System.out.println(-1.0/0.0);
}
}

Difference between number/10 and number*0.1 in java

I've been working on an interview question for 1.5 hours and could not find the bug in my Java program.
And then I found what the problem was, which I don't understand (don't pay attention to the values, there were others, it's about the types):
int size=100;
Integer a=12;
if(a >= size/10)...
//didn't work
is different than
if(a >= size*0.1)...
//worked
I understand that there is a conversion, but still, how is it possible that with a=12, if(a>=size/10) returns false?
Why is that?
/10 is integer division. While *0.1 first converts the first operand to a double and performs a floating point multiplication.
If you use the /10, and the operand is 14, it will result in 1 indeed, 14/10=1.4 but integer division rounds this down. Thus 29/10=2.
If you use *0.1, the Java compiler will first convert the value of size to a double, thus 14.0 and then muliplies it with 0.1 resulting in 1.4.
On the other hand it's not all beaty that comes out of floating points. float and double can't represent every integer, and round off after computation.
For the given values for size however, it will result in the effect because 100 is a multiple of 10 and a float or double is capable of representing any integer value in the range from zero to hundred.
Finally /10 is not always an integer division: if the first operand is a floating point (e.g. 14.0d/10), the compiler will convert this to a floating point division.
Short version:
int/int is an integer division that rounds down to the nearest (lower) integer.
int*double is a double multiplication that - with rounding off errors - results in the floating point value, nearest to the correct result (with decimal digits).
I just tested here:
public class a {
public static void main(String[] args) {
int size = 100;
int a = 12;
System.out.println((a >= size / 10) ? "OK" : "Failed?");
}
}
And it worked. I don't think this is your real problem. Probably it's in another part of your code.

different result in java how can it be rectified

Simple calculation gives different result in java.
int a=5363/12*5;
out.println(a);// result is 2230
But actually result should be 2234.5
How can this java result be rectified?
Two issues:
The expression 5363/12*5 gives an integer result (in particular, the division is integer).
The variable a is of type int (integer).
To fix:
double a=5363.0/12*5;
out.println(a);
Note that in general you can't expect to get exact results when using floating-point arithmetic. The following is a very good read: What Every Computer Scientist Should Know About Floating-Point Arithmetic.
5363, 12, and 5 are all being interpreted as ints. the calculation actually being performed here is:
5363/12 = 446.9… - truncated to the int value 446
446 * 5 = 2230
Try specifying a as a float, and indicate that the numbers in the calculation are also created as floats:
float a = 5363f/12f*5f
Take a as double.
Taking a as int will round it to the integer.
Because your all the literal numbers in the right hand side are integers (e.g. 5363 as opposed to 5363.0) expression is being calculated using integer arithmetic semantics i.e. / does whole number division. Thus 5262/12 equals 446 and 446*5 equals 2230. Also your variable a is an int which can only ever hold an integer value.
To fix this you need to do two things. Change the type of a to a decimal type e.g. float or double b) have at least one of 5363 and 12 represented as a decimal type e.g.
double a= 5363.0/12.0*5
Instead of using double you can re-order your expression.
Assuming 5363/12*5 = 5363*5/12 this will give you a closer answer. You have commented you want to round the result so instead you have to add half the value you are dividing by.
int a = (5363 * 5 + /* for rounding */ 6) / 12;
System.out.println(a);
prints
2235
An int is an Integer - nothing after the ..
You should be using
double a = 5363d/12*5;
It seems it has some int/double rounding issue:
double a=((double)5363/12)*5;
System.out.println("VALUE: "+a);
Prints:
VALUE: 2234.5833333333335
Edit: rounding the result to an integer value:
double a=((double)5363/12)*5;
long b=Math.round(a); //you can cast it to an int type if needed
System.out.println("ROUNDED: "+b);
Prints:
ROUNDED: 2235
Use double
double a = 5363/12*5;
System.out.println(a);
or
cast the integer, to prevent loss or precision.
int a = ((int) 5363/12*5);
System.out.println(a);

Floating point rounding (in java)

What is the best way of determining if a given float(or double) has no significant decimal places.
f(234.0) = true
f(34.45) = false
f(3.1322) = false
i.e. equivalent of
EQ(((int)number) * 1.0 , number)
where EQ is a given method to compare floating points and it is OK to assume that the float fits in an integer.
Math.rint(x) == x
Math.rint() returns a double, so it also works for large numbers where the long result of Math.round() overflows.
Note that this also gives true for positive and negative infinity. You can explicitly exclude them by Math.rint(x) == x && !Double.isInfinite(x).
Round the value to the nearest integer, and calculate the absolute difference to the actual value.
If that difference is less than a certain percentage of the actual value you are close "enough".
You could try something like this:
public static boolean f(double d) {
return d % 1 == 0;
}

Categories