计算双值最接近的优选十进制结果 [英] Compute the double value nearest preferred decimal result

查看:168
本文介绍了计算双值最接近的优选十进制结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

令N(x)是具有最小有效数字
的十进制数字的值,使得x是最接近数字值的 double



给定 double 值a和b,我们如何计算双重值最近N(b)-N(a)?



例如: p>


  • 如果a和b是最接近的.2和.3的 double >

    • 所需的结果是最接近的$ double 值,


      • 0.1000000000000000055511151231257827021181583404541015625,


    • 而不是直接减去a和b的结果,

      • 0.0999999999999997779553950749686919152736663818359375。




解决方案

作为基准:在Java中, Double.toString()提供描述的N(x)在这个问题上,回归价值作为数字。可以使用a和b的字符串,用小学方法减去它们,并将生成的字符串转换为 double



这表明使用现有库例程解决问题是相当可行的。这样做可以改善解决方案。我建议您探索:




  • 是否有函数D(x)返回小数位后的有效数字, N(x)的?如果是这样,我们可以乘以a和b乘以D(a)和D(b)确定的幂,以便产生正确的整数结果(对于它们可表示为 double的情况) 值),减去它们,并除以十的幂。

  • 我们可以确定哪些 ba 或者一些简单的表达式可以快速地舍入到小数点附近的东西,绕过更难的情况所需的代码?例如,我们可以证明对于一定范围内的数字,(round(10000 * b)-round(10000 * a))/ 10000 总是产生所需的结果? / li>

Let N(x) be the value of the decimal numeral with the fewest significant digits such that x is the double value nearest the value of the numeral.

Given double values a and b, how can we compute the double value nearest N(b)-N(a)?

E.g.:

  • If a and b are the double values nearest .2 and .3,
    • the desired result is the double value nearest .1,
      • 0.1000000000000000055511151231257827021181583404541015625,
    • rather than than the result of directly subtracting a and b,
      • 0.09999999999999997779553950749686919152736663818359375.

解决方案

As a baseline: In Java, the Double.toString() provides the N(x) function described in the question, returning its value as a numeral. One could take the strings for a and b, subtract them with the elementary-school method, and convert the resulting string to double.

This demonstrates solving the problem is quite feasible using existing library routines. This leaves the task of improving the solution. I suggest exploring:

  • Is there a function D(x) that returns the number of significant digits after the decimal place for the numeral described in N(x)? If so, can we multiply a and b by a power of ten determined by D(a) and D(b), round as necessary to produce the correct integer results (for situations where they are representable as double values), subtract them, and divide by the power of ten?
  • Can we establish criteria for which b-a or some simple expression can be quickly rounded to something near a decimal numeral, bypassing the code that would be necessary for harder cases? E.g., could we prove that for numbers within a certain range, (round(10000*b)-round(10000*a))/10000 always produces the desired result?

这篇关于计算双值最接近的优选十进制结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆