开发者

Python: avoiding fraction simplification

I'm working on a music app' in Python and would like to use the fractions module to handle time signatures amongst other things. My problem is that fr开发者_JAVA技巧actions get simplified, i.e.:

>>> from fractions import Fraction
>>> x = Fraction(4, 4)
>>> x
Fraction(1, 1)

However, it is important from a musical point of view that 4/4 stays 4/4 even though it equals 1. Is there any built-in way to avoid that behaviour?

Thanks!


Yes: make a custom class for it.

Musical time signatures are not fractions, so it doesn't make sense to represent them with a math class.


You should use some data structure other than Fraction. Just a plain tuple would be simplest, though you could also make your own class. If you need to do calculations, do them on the individual integers that make up the time signature.


No, there is not – division by the GCD is built into the Fraction class operations. Other reasons you would probably want to create a custom class anyway, at least if you're working with musical notation, are:

  • to be able to handle common time (C) and cut time (slash-C) substitutions for 4/4 and 2/4 – or even better, to make that optional
  • to be able to represent compound time signatures (e.g. 2+3+2/8)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜