2011-11-14 5 views
14

で、私は次の問題に実行しているよ:パイソン - 丸めは準々間隔

10.38

11.12

5.24

9.76

のような様々な数を考えます

既に組み込みの関数が存在し、 > 10.50

11.12 - - > 11.00

5.24 - > 5.25

9.76 - > 9-75例えば様最も近い0.25ステップ:

10.38のm個のアップ?

または、目的のタスクを実行する関数を一緒にハックすることはできますか?

事前に感謝し、よろしく

ダンは

答えて

24
>>> def my_round(x): 
... return round(x*4)/4 
... 
>>> 
>>> assert my_round(10.38) == 10.50 
>>> assert my_round(11.12) == 11.00 
>>> assert my_round(5.24) == 5.25 
>>> assert my_round(9.76) == 9.75 
>>> 
+0

*頭--->デスク*確かに些細なこと - 私は午前5時にコーディングを中止します。 ありがとうpulegiumと6502 – Daniyal

4

には組み込みありませんが、そのような機能は、これは

def roundQuarter(x): 
    return round(x * 4)/4.0 
26

書くことは簡単です任意の解像度への丸めを可能にする汎用ソリューションです。特定のケースでは、解像度として0.25を指定するだけでよいのですが、テストケースに示すように他の値も可能です。

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

print "Rounding to quarters" 
print roundPartial (10.38, 0.25) 
print roundPartial (11.12, 0.25) 
print roundPartial (5.24, 0.25) 
print roundPartial (9.76, 0.25) 

print "Rounding to tenths" 
print roundPartial (9.74, 0.1) 
print roundPartial (9.75, 0.1) 
print roundPartial (9.76, 0.1) 

print "Rounding to hundreds" 
print roundPartial (987654321, 100) 

この出力:

Rounding to quarters 
10.5 
11.0 
5.25 
9.75 
Rounding to tenths 
9.7 
9.8 
9.8 
Rounding to hundreds 
987654300.0 
+0

美しいジェネリックソリューション。どのようにすべてのソリューションを「受け入れられた回答」としてマークすることができますか? – Daniyal

+3

@ダニヤル:できません。私の通常の行動は、もし答えが、メリットでソートされていなければ、最も低い議員を持つ男にそれを(upvoteと共に)与えて、他の人をupvoteすることです。この場合、残念ながらそれは私のものではありません:-) – paxdiablo

2

paxdiabloの溶液を少し向上させることができます。

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

ですので、関数は「データ型に敏感です」。