Skip to content

Instantly share code, notes, and snippets.

@kenichiice
Last active April 1, 2024 05:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenichiice/428bff42e1f09c4809f7965177ed024c to your computer and use it in GitHub Desktop.
Save kenichiice/428bff42e1f09c4809f7965177ed024c to your computer and use it in GitHub Desktop.
混合基数の高速フーリエ変換
/*
Copyright 2024 OGAWA KenIchi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <chrono>
#include <cmath>
#include <complex>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <numbers>
#include <random>
#include <unordered_map>
#include <vector>
template<typename T>
using twiddle_factor_map =
std::unordered_map<std::size_t, std::vector<std::complex<T>>>;
namespace detail
{
// nの約数を返す
inline
std::size_t find_divisor(std::size_t n, std::size_t start = 2)
{
for (std::size_t i = start; i * i < n; ++i) {
if (n % i == 0) return i;
}
return n;
}
// 範囲[first, last)の値を離散フーリエ変換した結果を範囲[first, last)に上書きする。
// work_firstは[first, last)と同じサイズの作業用範囲の先頭。
// radixには範囲[first, last)の要素数の約数を指定する。
template<typename T, typename Iter>
void fft(
Iter first,
Iter last,
Iter work_first,
std::size_t radix,
const twiddle_factor_map<T>& tf_map)
{
const auto n = static_cast<std::size_t>(std::distance(first, last));
if (n <= 1) return;
const auto& tfs_r = tf_map.at(radix);
const auto& tfs_n = tf_map.at(n);
const auto s = n / radix;
for (std::size_t i = 0; i < s; ++i) {
auto it = work_first + i;
for (std::size_t j = 0; j < radix; ++j) {
*it = 0;
for (std::size_t k = 0; k < radix; ++k) {
*it += *(first + i + s * k) * tfs_r[j * k % radix];
}
*it *= tfs_n[i * j];
it += s;
}
}
for (std::size_t i = 0; i < radix; ++i) {
const auto it = work_first + s * i;
fft(it, it + s, first, find_divisor(s), tf_map);
}
for (std::size_t i = 0; i < s; ++i) {
auto it = first + radix * i;
for (std::size_t j = 0; j < radix; ++j) {
*it = *(work_first + i + s * j);
++it;
}
}
}
}
// 分母がnの回転因子列を作る
template<typename T>
std::vector<std::complex<T>> make_twiddle_factors(std::size_t n)
{
std::vector<std::complex<T>> result;
const auto theta = -2 * std::numbers::pi_v<T> / n;
for (std::size_t i = 0; i < n; ++i) {
result.push_back(std::polar<T>(1, theta * i));
}
return result;
}
// 要素数nのFFTに必要な回転因子列のマップを作る
template<typename T>
twiddle_factor_map<T> make_twiddle_factor_map(std::size_t n)
{
twiddle_factor_map<T> result;
result.try_emplace(n, make_twiddle_factors<T>(n));
for (auto d = detail::find_divisor(n); d != n; d = detail::find_divisor(n)) {
if (!result.contains(d)) result.try_emplace(d, make_twiddle_factors<T>(d));
n /= d;
if (!result.contains(n)) result.try_emplace(n, make_twiddle_factors<T>(n));
}
return result;
}
// inputの値を離散フーリエ変換した結果を返す
template<typename T>
std::vector<std::complex<T>> fft(
std::vector<std::complex<T>> input,
const twiddle_factor_map<T>& tf_map)
{
std::vector<std::complex<double>> work(input.size());
detail::fft(
input.begin(),
input.end(),
work.begin(),
detail::find_divisor(input.size()),
tf_map);
return input;
}
// inputの値を離散フーリエ変換した結果を返す。
// 素朴な実装により計算する。
template<typename T>
std::vector<std::complex<T>> dft(
const std::vector<std::complex<T>>& input,
const std::vector<std::complex<T>>& twiddle_factors)
{
const auto n = input.size();
std::vector<std::complex<T>> result(n);
for (std::size_t i = 0; i < n; ++i) {
for (std::size_t j = 0; j < n; ++j) {
result[i] += input[j] * twiddle_factors[i * j % n];
}
}
return result;
}
// fft()とdft()の両方で計算して結果を比較する
template<typename T>
void calc(const std::vector<std::complex<T>>& a)
{
namespace ch = std::chrono;
const auto t1 = ch::steady_clock::now();
const auto b1 = dft(a, make_twiddle_factors<T>(a.size()));
const auto t2 = ch::steady_clock::now();
const auto b2 = fft(a, make_twiddle_factor_map<T>(a.size()));
const auto t3 = ch::steady_clock::now();
const auto d1 = ch::duration_cast<ch::duration<double>>(t2 - t1).count();
const auto d2 = ch::duration_cast<ch::duration<double>>(t3 - t2).count();
T max_delta = 0;
for (std::size_t i = 0; i < a.size(); ++i) {
max_delta = std::max(max_delta, std::abs(b1[i] - b2[i]));
}
std::cout << std::fixed << std::setprecision(3)
<< "size\t" << a.size()
<< "\tratio\t" << std::right << std::setw(8) << d1 / d2
<< "\tdft\t"<< std::right << std::setw(8) << d1
<< "\tfft\t" << std::right << std::setw(8) << d2
<< "\tdelta\t" << std::scientific << max_delta
<< std::endl;
}
int main()
{
std::minstd_rand rand;
std::uniform_real_distribution<double> urd{-10, 10};
std::vector<std::complex<double>> input = { {urd(rand), urd(rand) }, { urd(rand), urd(rand) } };
// 1回目の計算だけ時間がかかってしまうようなのでここでダミーの計算をしている
dft(input, make_twiddle_factors<double>(2));
std::cout << "--- 2000まで ---" << std::endl;
for (int i = 2; i < 2000; ++i) {
input.resize(i, { urd(rand), urd(rand) });
calc(input);
}
std::cout << "--- 2のべき乗 ---" << std::endl;
for (int i = 2; i < 100000; i *= 2) {
input.resize(i, { urd(rand), urd(rand) });
calc(input);
}
// 3のべき乗
std::cout << "--- 3のべき乗 ---" << std::endl;
for (int i = 3; i < 100000; i *= 3) {
input.resize(i, { urd(rand), urd(rand) });
calc(input);
}
// 素数の積
std::cout << "--- 素数の積 ---" << std::endl;
std::size_t s = 1;
for (auto i : { 2, 3, 5, 7, 11, 13 }) {
s *= i;
input.resize(s, { urd(rand), urd(rand) });
calc(input);
}
// 素数
std::cout << "--- 素数 ---" << std::endl;
for (auto i : { 2, 3, 5, 7, 11, 13, 1009, 10009, 100003 }) {
input.resize(i, { urd(rand), urd(rand) });
calc(input);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment