1

I have known that if we want to prevent overflow for integer type we can use long type to take it and compare the long type with Integer.MAX_VALUE. So how about float value?

for example

// Question: How do I prevent float overflow
    private float distance(Point p, Cluster c){
        float px = p.getX(), py = p.getY(), cx = c.getXMean(), cy = c.getYMean();

        return (px - cx) * (px - cx) + (py - cy) * (py - cy);
    }
Czon
  • 299
  • 1
  • 4
  • 6
  • 1
    You want to convert a string to float & check overflow? Post your code. – LHA Nov 05 '15 at 16:41
  • 1
    What's wrong with `Float.MAX_VALUE`? http://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#MAX_VALUE – skypjack Nov 05 '15 at 16:42
  • 1
    there are various [ways to detect overflow](http://stackoverflow.com/q/199333/995714) without the use of `long`. For float case, the simplest way is `double` – phuclv Nov 05 '15 at 16:48
  • @skypjack we need a larger scale type to compare with Float.MAX_VALUE right like int a; long rst = a * a; if(rst >= Integer.MAX_VALUE) return Integer.MAX_VALUE; – Czon Nov 05 '15 at 16:55
  • @Czon what's wrong with `double`s and `Float.MAX_VALUE`? – skypjack Nov 05 '15 at 16:58
  • 2
    Also, please define `overflow` for float? Float is stored quite differently in memory compared with integers, it does not overflow for a long time it just loses huge chunks of precision. Are you sure that in your case precision does not matter, and the main problem is overflowing the maximal possible value (which is somewhere about 3.8*10^38, that is 38 zeroes)? – bezmax Nov 05 '15 at 17:02
  • 1
    Usually only integer and (long) overflows are an issue, where formulas are adapted such that an overlow will not occure when the input arguments are a value near Integer.MAX_VALUE. for floats the precision is the topic, which is easily solved to change to double. – AlexWien Nov 05 '15 at 17:04

1 Answers1

2

Try this:

    double doubleValue = (px - cx) * (px - cx) + (py - cy) * (py - cy);

    double posDouble = (doubleValue >= 0) ? doubleValue : (doubleValue * -1);

    if (posDouble != 0 && (posDouble < Float.MIN_VALUE || posDouble > Float.MAX_VALUE)) {
        throw new Exception("Overflow");
    }

    return (float)doubleValue;

Source code:

http://grepcode.com/file_/repo1.maven.org/maven2/commons-beanutils/commons-beanutils/1.9.0/org/apache/commons/beanutils/locale/converters/FloatLocaleConverter.java/?v=source

LHA
  • 9,398
  • 8
  • 46
  • 85