- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有 C++ FFT 代码(粘贴在下面)。
在 C++ 中,当我在 main() 中输入时,RL_Input = {1,2,-3,4}, IM_Input = {-4,3,2,1},我得到的答案是 RL_Output = {4, 6, -8, 2}, IM_Output = {2, -4, -6, -8}。
我想从 SWIFT 调用此 C++ 代码。所以,在 SWIFT 中,我想做如下事情:
let (RL_Output, IM_Output) = Some_Swift_Function([1,2,-3,4], [-4,3,2,1]) // INPUT RL & IM
print(RL_Output)
print(IM_Output)
// RL_Output = [4, 6, -8, 2] //Answer (REAL)
// IM_Output = [2, -4, -6, -8] //Answer (IMAG)
如何使用我拥有的 C++ 代码(如下所示)执行上述操作?
//FftRealPairTest.cpp
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <random>
#include <vector>
#include "FftRealPair.hpp"
using std::cout;
using std::endl;
using std::vector;
int main() {
vector<double> inputreal({1,2,-3,4});
vector<double> inputimag({-4,3,2,1});
vector<double> actualoutreal(inputreal);
vector<double> actualoutimag(inputimag);
Fft::transform(actualoutreal, actualoutimag);
std::cout << "REAL:" << std::endl;
for (int i = 0; i < inputimag.size(); ++i)
{
std::cout << actualoutreal[i] << std::endl;
}
std::cout << "IMAG" << std::endl;
for (int i = 0; i < inputimag.size(); ++i)
{
std::cout << actualoutimag[i] << std::endl;
}
}
/////////////////////////////////////////////////
//FftRealPair.cpp
/*
* Free FFT and convolution (C++)
*
* Copyright (c) 2017 Project Nayuki. (MIT License)
* https://www.nayuki.io/page/free-small-fft-in-multiple-languages
*
* 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 <algorithm>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include "FftRealPair.hpp"
using std::size_t;
using std::vector;
// Private function prototypes
static size_t reverseBits(size_t x, int n);
void Fft::transform(vector<double> &real, vector<double> &imag) {
size_t n = real.size();
if (n != imag.size())
throw "Mismatched lengths";
if (n == 0)
return;
else if ((n & (n - 1)) == 0) // Is power of 2
transformRadix2(real, imag);
else // More complicated algorithm for arbitrary sizes
transformBluestein(real, imag);
}
void Fft::inverseTransform(vector<double> &real, vector<double> &imag) {
transform(imag, real);
}
void Fft::transformRadix2(vector<double> &real, vector<double> &imag) {
// Length variables
size_t n = real.size();
if (n != imag.size())
throw "Mismatched lengths";
int levels = 0; // Compute levels = floor(log2(n))
for (size_t temp = n; temp > 1U; temp >>= 1)
levels++;
if (static_cast<size_t>(1U) << levels != n)
throw "Length is not a power of 2";
// Trignometric tables
vector<double> cosTable(n / 2);
vector<double> sinTable(n / 2);
for (size_t i = 0; i < n / 2; i++) {
cosTable[i] = std::cos(2 * M_PI * i / n);
sinTable[i] = std::sin(2 * M_PI * i / n);
}
// Bit-reversed addressing permutation
for (size_t i = 0; i < n; i++) {
size_t j = reverseBits(i, levels);
if (j > i) {
std::swap(real[i], real[j]);
std::swap(imag[i], imag[j]);
}
}
// Cooley-Tukey decimation-in-time radix-2 FFT
for (size_t size = 2; size <= n; size *= 2) {
size_t halfsize = size / 2;
size_t tablestep = n / size;
for (size_t i = 0; i < n; i += size) {
for (size_t j = i, k = 0; j < i + halfsize; j++, k += tablestep) {
size_t l = j + halfsize;
double tpre = real[l] * cosTable[k] + imag[l] * sinTable[k];
double tpim = -real[l] * sinTable[k] + imag[l] * cosTable[k];
real[l] = real[j] - tpre;
imag[l] = imag[j] - tpim;
real[j] += tpre;
imag[j] += tpim;
}
}
if (size == n) // Prevent overflow in 'size *= 2'
break;
}
}
void Fft::transformBluestein(vector<double> &real, vector<double> &imag) {
// Find a power-of-2 convolution length m such that m >= n * 2 + 1
size_t n = real.size();
if (n != imag.size())
throw "Mismatched lengths";
size_t m = 1;
while (m / 2 <= n) {
if (m > SIZE_MAX / 2)
throw "Vector too large";
m *= 2;
}
// Trignometric tables
vector<double> cosTable(n), sinTable(n);
for (size_t i = 0; i < n; i++) {
unsigned long long temp = static_cast<unsigned long long>(i) * i;
temp %= static_cast<unsigned long long>(n) * 2;
double angle = M_PI * temp / n;
// Less accurate alternative if long long is unavailable: double angle = M_PI * i * i / n;
cosTable[i] = std::cos(angle);
sinTable[i] = std::sin(angle);
}
// Temporary vectors and preprocessing
vector<double> areal(m), aimag(m);
for (size_t i = 0; i < n; i++) {
areal[i] = real[i] * cosTable[i] + imag[i] * sinTable[i];
aimag[i] = -real[i] * sinTable[i] + imag[i] * cosTable[i];
}
vector<double> breal(m), bimag(m);
breal[0] = cosTable[0];
bimag[0] = sinTable[0];
for (size_t i = 1; i < n; i++) {
breal[i] = breal[m - i] = cosTable[i];
bimag[i] = bimag[m - i] = sinTable[i];
}
// Convolution
vector<double> creal(m), cimag(m);
convolve(areal, aimag, breal, bimag, creal, cimag);
// Postprocessing
for (size_t i = 0; i < n; i++) {
real[i] = creal[i] * cosTable[i] + cimag[i] * sinTable[i];
imag[i] = -creal[i] * sinTable[i] + cimag[i] * cosTable[i];
}
}
void Fft::convolve(const vector<double> &x, const vector<double> &y, vector<double> &out) {
size_t n = x.size();
if (n != y.size() || n != out.size())
throw "Mismatched lengths";
vector<double> outimag(n);
convolve(x, vector<double>(n), y, vector<double>(n), out, outimag);
}
void Fft::convolve(
const vector<double> &xreal, const vector<double> &ximag,
const vector<double> &yreal, const vector<double> &yimag,
vector<double> &outreal, vector<double> &outimag) {
size_t n = xreal.size();
if (n != ximag.size() || n != yreal.size() || n != yimag.size()
|| n != outreal.size() || n != outimag.size())
throw "Mismatched lengths";
vector<double> xr(xreal);
vector<double> xi(ximag);
vector<double> yr(yreal);
vector<double> yi(yimag);
transform(xr, xi);
transform(yr, yi);
for (size_t i = 0; i < n; i++) {
double temp = xr[i] * yr[i] - xi[i] * yi[i];
xi[i] = xi[i] * yr[i] + xr[i] * yi[i];
xr[i] = temp;
}
inverseTransform(xr, xi);
for (size_t i = 0; i < n; i++) { // Scaling (because this FFT implementation omits it)
outreal[i] = xr[i] / n;
outimag[i] = xi[i] / n;
}
}
static size_t reverseBits(size_t x, int n) {
size_t result = 0;
for (int i = 0; i < n; i++, x >>= 1)
result = (result << 1) | (x & 1U);
return result;
}
////////////////////////////////////////////////////
//FftRealPair.hpp
/*
* Free FFT and convolution (C++)
*
* Copyright (c) 2017 Project Nayuki. (MIT License)
* https://www.nayuki.io/page/free-small-fft-in-multiple-languages
*
* 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.
*/
#pragma once
#include <vector>
namespace Fft {
/*
* Computes the discrete Fourier transform (DFT) of the given complex vector, storing the result back into the vector.
* The vector can have any length. This is a wrapper function.
*/
void transform(std::vector<double> &real, std::vector<double> &imag);
/*
* Computes the inverse discrete Fourier transform (IDFT) of the given complex vector, storing the result back into the vector.
* The vector can have any length. This is a wrapper function. This transform does not perform scaling, so the inverse is not a true inverse.
*/
void inverseTransform(std::vector<double> &real, std::vector<double> &imag);
/*
* Computes the discrete Fourier transform (DFT) of the given complex vector, storing the result back into the vector.
* The vector's length must be a power of 2. Uses the Cooley-Tukey decimation-in-time radix-2 algorithm.
*/
void transformRadix2(std::vector<double> &real, std::vector<double> &imag);
/*
* Computes the discrete Fourier transform (DFT) of the given complex vector, storing the result back into the vector.
* The vector can have any length. This requires the convolution function, which in turn requires the radix-2 FFT function.
* Uses Bluestein's chirp z-transform algorithm.
*/
void transformBluestein(std::vector<double> &real, std::vector<double> &imag);
/*
* Computes the circular convolution of the given real vectors. Each vector's length must be the same.
*/
void convolve(const std::vector<double> &x, const std::vector<double> &y, std::vector<double> &out);
/*
* Computes the circular convolution of the given complex vectors. Each vector's length must be the same.
*/
void convolve(
const std::vector<double> &xreal, const std::vector<double> &ximag,
const std::vector<double> &yreal, const std::vector<double> &yimag,
std::vector<double> &outreal, std::vector<double> &outimag);
}
最佳答案
如果您想从 Swift 调用该 C++ 代码,则需要通过 Objective-C++ 进行桥接。在 SO 上进行简单搜索将显示有关如何执行此操作的大量帖子。
在这种情况下,我们希望尽量减少数据复制,因为我们将 C++/Objective-C++/Swift 粘合在一起,以减少对性能的负面影响。 Swift 中 Double
的 Array
将其数据存储在连续存储中,因为 Double
不是一个类。 Array
的withUnsafeMutableBufferPointer
方法似乎是一个很有前途的解决方案。不过,我会小心,并首先在一个简单的测试程序上测试这种方法。如果时间允许,我会在接下来的几天里想出一些办法。
请参阅位于 https://developer.apple.com/documentation/swift/array 的 Array
文档.另一个非常有用的资源是 https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/index.html#//apple_ref/doc/uid/TP40014216-CH2-ID0 ,您可能已经在搜索此主题时看到了它。
一般要注意的一件事是,如果调整 vector 的大小,C++ 中的 vector
存储可以在内存中重新定位,例如,在这种情况下,我们将不得不制作额外的数据拷贝从 Swift 桥接到 C++ 时。然而,这段 C++ 代码似乎没有做任何会移动底层存储的事情。
2017 年 10 月 25 日更新:使用 withUnsafeMutableBufferPointer
将需要在内存中复制数组,因为创建一个直接就地使用给定的 vector
是有问题的缓冲。参见 How to cheaply assign C-style array to std::vector? .
但是,由于有一个 C 版本的库可用,这就变得小菜一碟了:
fft.h
和 fft.c
添加到您的 Xcode 项目。fft.h
。然后你可以像这样在 Swift 中使用 C 代码:
var dReal : [Double] = [1,2,-3,4]
var dImg : [Double] = [-4,3,2,1]
dReal.withUnsafeMutableBufferPointer { (real : inout UnsafeMutableBufferPointer<Double> ) in
dImg.withUnsafeMutableBufferPointer { (img : inout UnsafeMutableBufferPointer<Double>) in
if (real.count == img.count) {
Fft_transform(real.baseAddress, img.baseAddress, real.count)
}
}
}
当然,这只是一个简单的示例。你可以让它更漂亮,添加错误处理等。
关于c++ - 在 SWIFT 中使用 C++ FFT 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46904905/
我需要将文本放在 中在一个 Div 中,在另一个 Div 中,在另一个 Div 中。所以这是它的样子: #document Change PIN
奇怪的事情发生了。 我有一个基本的 html 代码。 html,头部, body 。(因为我收到了一些反对票,这里是完整的代码) 这是我的CSS: html { backgroun
我正在尝试将 Assets 中的一组图像加载到 UICollectionview 中存在的 ImageView 中,但每当我运行应用程序时它都会显示错误。而且也没有显示图像。 我在ViewDidLoa
我需要根据带参数的 perl 脚本的输出更改一些环境变量。在 tcsh 中,我可以使用别名命令来评估 perl 脚本的输出。 tcsh: alias setsdk 'eval `/localhome/
我使用 Windows 身份验证创建了一个新的 Blazor(服务器端)应用程序,并使用 IIS Express 运行它。它将显示一条消息“Hello Domain\User!”来自右上方的以下 Ra
这是我的方法 void login(Event event);我想知道 Kotlin 中应该如何 最佳答案 在 Kotlin 中通配符运算符是 * 。它指示编译器它是未知的,但一旦知道,就不会有其他类
看下面的代码 for story in book if story.title.length < 140 - var story
我正在尝试用 C 语言学习字符串处理。我写了一个程序,它存储了一些音乐轨道,并帮助用户检查他/她想到的歌曲是否存在于存储的轨道中。这是通过要求用户输入一串字符来完成的。然后程序使用 strstr()
我正在学习 sscanf 并遇到如下格式字符串: sscanf("%[^:]:%[^*=]%*[*=]%n",a,b,&c); 我理解 %[^:] 部分意味着扫描直到遇到 ':' 并将其分配给 a。:
def char_check(x,y): if (str(x) in y or x.find(y) > -1) or (str(y) in x or y.find(x) > -1):
我有一种情况,我想将文本文件中的现有行包含到一个新 block 中。 line 1 line 2 line in block line 3 line 4 应该变成 line 1 line 2 line
我有一个新项目,我正在尝试设置 Django 调试工具栏。首先,我尝试了快速设置,它只涉及将 'debug_toolbar' 添加到我的已安装应用程序列表中。有了这个,当我转到我的根 URL 时,调试
在 Matlab 中,如果我有一个函数 f,例如签名是 f(a,b,c),我可以创建一个只有一个变量 b 的函数,它将使用固定的 a=a1 和 c=c1 调用 f: g = @(b) f(a1, b,
我不明白为什么 ForEach 中的元素之间有多余的垂直间距在 VStack 里面在 ScrollView 里面使用 GeometryReader 时渲染自定义水平分隔线。 Scrol
我想知道,是否有关于何时使用 session 和 cookie 的指南或最佳实践? 什么应该和什么不应该存储在其中?谢谢! 最佳答案 这些文档很好地了解了 session cookie 的安全问题以及
我在 scipy/numpy 中有一个 Nx3 矩阵,我想用它制作一个 3 维条形图,其中 X 轴和 Y 轴由矩阵的第一列和第二列的值、高度确定每个条形的 是矩阵中的第三列,条形的数量由 N 确定。
假设我用两种不同的方式初始化信号量 sem_init(&randomsem,0,1) sem_init(&randomsem,0,0) 现在, sem_wait(&randomsem) 在这两种情况下
我怀疑该值如何存储在“WORD”中,因为 PStr 包含实际输出。? 既然Pstr中存储的是小写到大写的字母,那么在printf中如何将其给出为“WORD”。有人可以吗?解释一下? #include
我有一个 3x3 数组: var my_array = [[0,1,2], [3,4,5], [6,7,8]]; 并想获得它的第一个 2
我意识到您可以使用如下方式轻松检查焦点: var hasFocus = true; $(window).blur(function(){ hasFocus = false; }); $(win
我是一名优秀的程序员,十分优秀!