Convert double to float without Infinity

后端 未结 4 1921
南笙
南笙 2021-01-17 07:26

I\'m converting double to float using ye old float myFloat = (float)myDouble.

This does however sometimes result in \"Infinity\", which is not good for

4条回答
  •  半阙折子戏
    2021-01-17 08:05

    If a calculation result of a calculation exceeds the range of the type you're storing it in, it will be necessary to do one of three things:

    1. Throw an exception
    2. Return a "sentinel" value which indicates that there was a problem, and which will preferably be recognized as effectively invalidating any calculations where it appears
    3. Peg the result to some particular value (to which it would be pegged even it if it didn't exceed the range of your numeric type). For example, one may have a sensor assembly with two time-averaged inputs X and Y, whose "value" is (X*X)/(Y*Y)-(Y*Y)/(X*X). If the inputs are noisy, a low value on one input may be read as an exceptionally low value. If the measurement will be used to control a feedback loop, and if the "actual" value won't exceed +/- 1000000.0, it may be better to peg the value to that range than to let the control loop see a totally wild computed reading (X or Y being the smallest possible non-zero value).

    There are many applications where the third approach would be the right one. In such situations, however, if it would make sense to peg the reading at a value of a million, then it shouldn't matter whether the computation results in a value of 1,000,001 or 1E+39 (floating-point +INF). One should peg to a million in either case.

提交回复
热议问题