开发者

can't really manage a map of <Float,Object> (EDITED)

开发者 https://www.devze.com 2023-04-06 16:36 出处:网络
I have a map<Float,Object>. I need it store valuse like 0.01 ->ObjA 0.02 ->ObjB and sometimes 0.001 ->ObjA

I have a

   map<Float,Object>.

I need it store valuse like

0.01 ->ObjA

0.02 ->ObjB

and sometimes

0.001 ->ObjA

0.002 ->ObjB (thre开发者_如何学Goe digits after the dot)

I thought it would be easy.

But I have notice that when I calculate simple calculation with the float

I sometimes get stuff like this.

0.09998

0.02001 ----- instead of (0.01, 0.02)

I know that float isnt that good for that usage so I have tried double and clearly I got a map filled with

0.0999999998

0.0200000001

naturally.

So I think I should round it. but it is not that easy since I dont know to which size.

sometimes it should be 0.03 and sometimes 0.3.

Thanks for your assistance.



EDIT: Thanks for all the answers. I think my problem is that I get 5.00001 instead of 5 . not that I enter 5.000001 to a map. I would like to round the float and each time to the best value I can find . and since it is alwas 0.0000000X or 0.999999X I think It should be easy. But I haven't figured it out yet.



Try using

Map<BigDecimal, Object> 

BigDecimal will allow you to define floating point values exactly.


It sounds like you might want Map<BigDecimal, Object> if you're performing operations which are logically "accurate" within decimal arithmetic.

Alternatively, you might want a Map<Integer, Object> where 0.01 would map to 10, 0.001 would map to 1 etc. It's hard to know for sure without more information on what you're trying to do - but using Float or Double as the key in a map is likely to give you problems in all cases.


If you want to work with accurate values use java.math.BigDecimal instead of Float or Double (the API is a bit obscure).


Float number can't represent all decimal numbers. That's the reason.

A clear example is 0.1, this number can't be written in a float, and that's why you get that number, it's your 0.1

My suggestion? Don't use float as keys, for a single 0.000001 you can miss something that is in your list


Floating point numbers usually work with absolute or relative tolerances rather than values: "I want this object when a float is between X and Y or X +/- Y."

If that's the case for you, I'd recommend trying another approach - this won't do.


Just don't use float (or doubles, or even BigDecimals) as keys. You will have unexpected errors, specially if you create keys making operations. If you want a number for key, and you can handle some accuracy errors, use a Map and use your original floats * 10000 as keys. Even better, create a class CustomMap that wraps a Map, and implement only put(float key, Object value){ map.put(10000 * key, value)} and get(float), if you don't need the whole Map semantic.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号