开发者

Compare "similar" numbers in Python

In order to sync my iPod and my local music repository, I created a unique key for each track using its metadata. The unique track consists of the track's following metadata fields: artist, album, track number, duration. The iPod saves the track's duration in milliseconds, but my local repository saves it in seconds. For example: 437590 milliseconds on iPod is 438 seconds in my Local repository.

When I divide the ipod's track duration by 1000 I get 437. I开发者_运维百科 tried using round(), but round (b.tracklen/1000) prints 437.

I can hack this by checking math.ceil(), math.floor() for the iPod duration if there is no match but it's a lousy solution.

What is the best approach to this issue?


Your round call is giving the wrong result as you're dividing by 1000, instead of 1000.0

>>> round(437590/1000.0)
438.0


You are experiencing Python 2's integer division. When you divide two integers, Python (and many other languages) throw away the remainder. You'll want to divide by a float instead of an integer, as Dogbert indicated.


Rounding the result of an integer division is very easy: (n+(d/2))/d. In your case:

def RoundedDivide(value, divisor):
    return (value + (divisor/2)) / divisor

>>> RoundedDivide(437590, 1000)
438


Honestly, I think you nailed it already with the floor and ceil calls, but for somplicity you might want to do floor((ipodtime/1000)+1) == localrepostime to check equality since the ipod time seems to round down no matter what.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜