简体   繁体   English

度量单位 API (JSR-363) - 浮点错误

[英]Unit Of Measures API (JSR-363) - Floating Point Errors

We are using tec.units.unit-ri as an implementation of the JSR-363, javax.measure.unit-api.我们使用 tec.units.unit-ri 作为 JSR-363 javax.measure.unit-api 的实现。

We are using several weight-, length- and temperature- types in our application and we decided to use BigDecimal to store them.我们在应用程序中使用了几种重量、长度和温度类型,我们决定使用 BigDecimal 来存储它们。 While doing some conversions, I realized floating point errors were appearing in our instances.在进行一些转换时,我意识到我们的实例中出现了浮点错误。

Unit<Length> metres = Units.METRE;
Unit<Length> centimetres = Units.METRE.divide(100);
BigDecimal valueInCentimetres = new BigDecimal("10.1");
Quantity<Length> valueInMetres = Quantities.getQuantity(valueInCentimetres, centimetres).to(metres) ;

If I run this code, the variable valueInMetres contains a Double representation with a floating point error, 0.10099999999999999 m.如果我运行此代码,变量valueInMetres包含一个浮点错误为 0.10099999999999999 m 的Double表示。 The implementation uses double values internally, and loses precision while converting values.该实现在内部使用double精度值,并在转换值时失去精度。 We would need to round/introduce a scale to the value, which is not ideal.我们需要对值进行舍入/引入一个比例,这并不理想。

Is there anything obvious I am doing wrong here?有什么明显的我做错了吗? Have I missed some way of using the API which enables me to keep precision, or are all conversions routed over Double values and will lose precision, no matter what I do?我是否错过了某种使我能够保持精度的 API 使用方法,或者无论我做什么,所有转换都通过Double值路由并且会失去精度?

Searching further after asking this question, I realized that we used the wrong library for our application.在提出这个问题后进一步搜索,我意识到我们的应用程序使用了错误的库。 unit-ri is meant for Java ME and uses double internally, uom-se is meant for Java SE and uses BigDecimal. unit-ri用于 Java ME 并在内部使用 double, uom-se用于 Java SE 并使用 BigDecimal。 This solves our problem.这解决了我们的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM