【问题标题】:What is the best way to validate if a value with decimals is in a defined range验证带小数的值是否在定义范围内的最佳方法是什么
【发布时间】:2018-05-21 18:58:39
【问题描述】:

我有一个定义了阈值的文件,这些阈值用于帮助做出决定。

值如下所示:

"thresholds":[
    { "min": 0.0, "max": 0.25, "text": "VERY UNLIKELY" },
    { "min": 0.26, "max": 0.50, "text": "UNLIKELY" }
    { "min": 0.51, "max": 0.75, "text": "LIKELY" }
    { "min": 0.76, "max": 1.0, "text": "VERY LIKELY" }
]

条件:

for (Threshold threshold : thresholds) {
    if ((threshold.getMin() <= predictionValue) &&
        (predictionValue <= threshold.getMax())) {
            return threshold.getText();
    }
}

如果要检查的值类似于 0.2500000001,则它介于 0.25 和 0.26 之间。所以我问,确定一个值是否在一定范围内而没有空白的最佳方法是什么?

我应该添加一个精度参数并将此精度应用于最小值和最大值吗?我不想用像 0.259999999 这样的值来配置文件。

【问题讨论】:

  • 您可以将事物定义为不包括上限值的半开区间。示例: min: 0 - max 0.26 = min 和
  • @OHGODSPIDERS 是的好主意!
  • 如果你想要精确的小数,你可以使用 BigDecimal 类,确保你使用 BigDecimal(String val) 构造函数,因为如果你直接传递 double/float 它仍然是不精确的:docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html

标签: java decision-tree design-decisions


【解决方案1】:

您最终会得到这个灰色区域,因为您想声明一个包含 2 个值的边界。这不起作用。我会告诉你它是如何工作的:

你应该做什么:

"thresholds":[
    { "max": 0.25, "text": "VERY UNLIKELY" },
    { "max": 0.50, "text": "UNLIKELY" }
    { "max": 0.75, "text": "LIKELY" }
    { "max": 1.0, "text": "VERY LIKELY" }
]

以及条件:

for (Threshold threshold : thresholds) {
    if (predictionValue < threshold.getMax()) {
            return threshold.getText();
    }
}

如您所见,一个值足以定义边界。

【讨论】:

  • 是的,这可能是最好的处理方式。谢谢
猜你喜欢
  • 2011-04-13
  • 1970-01-01
  • 1970-01-01
  • 2010-09-21
  • 2018-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多