【问题标题】:Find the nearest value with a non-linear progression找到具有非线性级数的最接近的值
【发布时间】:2018-01-03 03:55:48
【问题描述】:

这有点复杂,但请耐心等待。我正在尝试创建一个将音符名称与其相应频率联系起来的地图。然后我想写一个函数,当提供一个随机频率时,它会返回最接近那个频率的音符。

这样做的问题是音符的频率不是用线性公式生成的,因此每个音符之间的确切中间频率也不是线性的。 (这基本上意味着音符之间的中点并不完全在中间,因此通过常规方法找到中点是行不通的。)

一些用于生成笔记地图的示例代码:

// Ordered starting with "B" so notes line up with frequencies
vector<string> names = {
    "B", "C", "C#/Db", "D", "D#/Eb", "E", "F", "F#/Gb", "G", "G#/Ab", "A", "A#/Bb"
};

double f0 = 440;
map<string, map<int, double> > notes;

// Map notes to their corresponding frequencies
for (int octave = 0; octave < 10; ++octave) {
    for (int index = 0; index < names.size(); ++index) {

        // Get the exact frequency of the musical note
        double frequency               = f0*pow(pow(2, 1.0/12), index       - 10)*pow(pow(2, 1.0/12), 12*(octave + 1 - 5));

        // Get the exact frequency between this note and the next (I'm not doing anything with this yet, but I feel like this is on the right track.)
        double frequency_between_notes = f0*pow(pow(2, 1.0/12), index + 0.5 - 10)*pow(pow(2, 1.0/12), 12*(octave + 1 - 5));

        notes[names[index]][octave] = frequency;
    }
}

我想写一个给定随机频率的函数,它将返回最接近该频率的音符。

Note& find_note(double frequency) {
    // Provided a random frequency find the ACTUAL nearest note using the non-linear formula that notes are calculated from.
    // Create the note object and return it.
}

Note 类看起来像这样:

class Note {
public:
    Note(string name, int octave, double frequency) {
        name_      = name;
        octave_    = octave;
        frequency_ = frequency;
    }

    const string& get_name() const {
        return name_;
    }

    const int& get_octave() const {
        return octave_;
    }

    const double& get_frequency() const {
        return frequency_;
    }
private:
    string name_;
    int    octave_;
    double frequency_;
};

用于计算音符频率的公式来自https://pages.mtu.edu/~suits/NoteFreqCalcs.html

如何在给定随机频率的情况下找到最近的音符?

【问题讨论】:

  • 只使用对数。
  • 你不能把方程倒过来找出你离 f0 的半步数,给你的随机频率吗?看看你的链接,我认为这有点像.. n = (log(fn)-log(440))/log(2^1/12)

标签: c++ algorithm dictionary math


【解决方案1】:

半音频率的对数是均匀分布的。要找到与给定频率最接近的音符,只需获取频率的对数并找到最接近的音符频率对数。

这是一个简单的函数,它以 Hz 为单位获取频率并返回最接近的半音,作为高于(正)或低于(负)A4 (440Hz) 的半音数

const double LOG_SEMITONE = log(2.0)/12.0;

int getNote(double f)
{
    double note = log(f/440.0) / LOG_SEMITONE;
    return (int)round(note);
}

【讨论】:

  • 这太棒了,我今晚回家一定要试一试。我从来都不擅长对数,所以这个想法从未在我脑海中闪过……
猜你喜欢
  • 1970-01-01
  • 2012-10-27
  • 2015-03-01
  • 2019-12-16
  • 2021-03-22
  • 1970-01-01
  • 2018-03-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多