ios - Swift iOS 中的叉积

标签 ios arrays xcode swift optimization

我正在尝试在两个向量 R^n 之间进行叉积,有什么办法可以以最优化的方式做到这一点吗?

我已经查看了加速库,但仍然找不到任何东西

最佳答案

A cross product can exist in Rn if and only if n=0, 1, 3 or 7

来源:http://www.math.csusb.edu/faculty/pmclough/CP.pdf

所以不,您肯定找不到任何库可以做到这一点。如果您指的是元素方面的,则可以使用 Accelerate。这是一个简短的测试:

import Accelerate

let n = 10_000_000

let a = (0..<n).map{ _ in Double(arc4random()) / Double(UInt32.max) }
let b = (0..<n).map{ _ in Double(arc4random()) / Double(UInt32.max) }

print("A: [\(a.prefix(10).map{ "\($0)" }.joinWithSeparator(", ")), ...]")
print("B: [\(b.prefix(10).map{ "\($0)" }.joinWithSeparator(", ")), ...]")

var result = [Double](count: n, repeatedValue: 0)

let start = mach_absolute_time()
vDSP_vmulD(a, 1, b, 1, &result, 1, UInt(n))
let stop = mach_absolute_time()

let time = Double(stop - start) / Double(NSEC_PER_SEC)

print("Time: \(time) for \(n) elements")
print("Result: [\(result.prefix(10).map{ "\($0)" }.joinWithSeparator(", ")), ...]")

输出:

A: [0.269752697849123, 0.851672558312228, 0.0668649589798564, 0.0955562389212559, 0.255900985620893, 0.93693982901446, 0.085282990495973, 0.732230591525377, 0.588338787804437, 0.952581417968632, ...]
B: [0.750105029379508, 0.0454008649209051, 0.863010750120275, 0.308104009904923, 0.700024090637459, 0.327355608653127, 0.679469040520366, 0.666848364208557, 0.0567599588671606, 0.623293806245386, ...]
Time: 0.024393279 for 10000000 elements
Result: [0.202342855345318, 0.0386666707767751, 0.0577051784059674, 0.0294412603830718, 0.179136854752495, 0.306712507998386, 0.0579471517250063, 0.488286772182162, 0.0333940853957349, 0.593738097764296, ...]

1000 万个元素 0.024 秒已经相当快了

关于ios - Swift iOS 中的叉积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38127835/

相关文章:

swift - 如何将 UILabel 添加到 ScrollView 以显示标签中的所有文本

iphone - 从 NSString 中删除前导和尾随的换行符

ios - 如何使用动画以编程方式隐藏和显示 WKInterfaceGroup?

ios - 如何将 sqlite 数据库中的图像显示到 UIImageView

ios - Realm Swift iOS - 由于未捕获的异常 'RLMException' 而终止应用程序,原因 : 'Realm accessed from incorrect thread'

ios - App Store 版本号 - 更改方案/最佳实践

java - 如何在自定义 HashMap 实现中创建 O(1) 时间复杂度的查找方法和插入方法?

javascript - 为什么 Array.prototype.fill() 的这个示例会抛出 TypeError?

iphone - iOS RTP 库/教程/示例

c - 指向二维数组的一维指针