Rounding numbers to a specific resolution

陌路散爱 提交于 2019-12-11 14:26:54

问题


I know many languages have the ability to round to a certain number of decimal places, such as with the Python:

>>> print round (123.123, 1)
    123.1
>>> print round (123.123, -1)
    120.0

But how do we round to an arbitrary resolution that is not a decimal multiple. For example, if I wanted to round a number to the nearest half or third so that:

123.123 rounded to nearest half is 123.0.
456.456 rounded to nearest half is 456.5.
789.789 rounded to nearest half is 790.0.

123.123 rounded to nearest third is 123.0.
456.456 rounded to nearest third is 456.333333333.
789.789 rounded to nearest third is 789.666666667.

回答1:


You can round to an arbitrary resolution by simply scaling the number, which is multiplying the number by one divided by the resolution (or, easier, just dividing by the resolution).

Then you round it to the nearest integer, before scaling it back.

In Python (which is also a very good pseudo-code language), that would be:

def roundPartial (value, resolution):
    return round (value / resolution) * resolution

print "Rounding to halves"
print roundPartial (123.123, 0.5)
print roundPartial (456.456, 0.5)
print roundPartial (789.789, 0.5)

print "Rounding to thirds"
print roundPartial (123.123, 1.0/3)
print roundPartial (456.456, 1.0/3)
print roundPartial (789.789, 1.0/3)

print "Rounding to tens"
print roundPartial (123.123, 10)
print roundPartial (456.456, 10)
print roundPartial (789.789, 10)

print "Rounding to hundreds"
print roundPartial (123.123, 100)
print roundPartial (456.456, 100)
print roundPartial (789.789, 100)

In that above code, it's the roundPartial function which provides the functionality and it should be very easy to translate that into any procedural language with a round function.

The rest of it, basically a test harness, outputs:

Rounding to halves
123.0
456.5
790.0
Rounding to thirds
123.0
456.333333333
789.666666667
Rounding to tens
120.0
460.0
790.0
Rounding to hundreds
100.0
500.0
800.0


来源:https://stackoverflow.com/questions/8118982/rounding-numbers-to-a-specific-resolution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!