2016-01-01 47 views
0

這是一個midi音符轉換器的頻率,但我似乎無法得到數學正常工作......特別是與math.log函數。這在大多數情況下會產生69.0的輸出......但如果我輸入440以下的任何數字,它通常會輸出「ValueError:數學域錯誤」。我應該如何解決?Frequency to Midi Converter蟒蛇數學錯誤

#d=69+12*log(2)*(f/440) 
    #f=2^((d-69)/12)*440 
    #d is midi, f is frequency 

    import math 
    f=raw_input("Type the frequency to be converted to midi: ") 
    d=69+(12*math.log(int(f)/440))/(math.log(2)) 
    print d` 

回答

1

這是因爲Python 2使用整數除法。低於440的任何數據將評估爲0,然後傳遞給math.log()

>>> 500/440 
1 
>>> 440/440 
1 
>>> 439/440 
0 
>>> math.log(0) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: math domain error 

最簡單的方法是使Python 3的風格所謂真師通過將該線在你的文件的頂部:

from __future__ import division 

現在的Python 2將表現爲你所料:

>>> 439/440 
0.9977272727272727 
>>> math.log(439/440) 
>>> math.log(439/440) 
-0.0022753138371355394 

作爲替代方案,可以將紅利和/或除數轉換爲浮動:

d=69+(12*math.log(int(f)/440.0))/(math.log(2)) 

d=69+(12*math.log(float(f)/440))/(math.log(2)) 
+0

非常感謝您解釋!它現在工作:D –

0

如果是Python 2,它看起來像一個整數除法使括號中的乘積不精確。嘗試以440.0除以代替。

+0

謝謝你的幫助!它現在有效:D –