Java 到 Swift - 如何在 Xcode 6 中使用 math.pow 和 math.exp

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28568330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:40:07  来源:igfitidea点击:

Java to Swift - How to use math.pow and math.exp in Xcode 6

javaiosxcodeswiftmath

提问by Matty

I'm in the process of trying to apply my java code to work under swift language and am running into some issues.

我正在尝试应用我的 java 代码在 swift 语言下工作,但遇到了一些问题。

Part of my code in Java makes use of the math.pow(number,power) and math.exp() but I'm not entirely sure of how I would go about using that in swift language.

我在 Java 中的部分代码使用了 math.pow(number,power) 和 math.exp() 但我不完全确定我将如何在 swift 语言中使用它。

For example, in Java:

例如,在 Java 中:

diffAggregate = 0;
for (kIndex = 0; kIndex < NK_VALUES.length; kIndex ++) {
    diffSegment = NKVALUES[kIndex];
    diffSegment *= Math.pow(rhoR, IK_VALUES[kIndex]);
    diffSegment *= Math.pow(tempR, JK_VALUES[kIndex]);
    iFactor = 0;
    if (LK_VALUES[kIndex] > 0 {
       diffSegment *= Math.exp(-1 * Math.pow(rhoR,LK_VALUES[kIndex]);
       iFactor = LK_VALUES[kIndex] * Math.pow(rhoR, LK_VALUES[kIndex]);
       }
    if (PK_VALUES[kIndex] > 0 {
       diffSegment *= Math.exp(-1 * PK_VALUES[kIndex] * Math.pow(rhoR, 2) - BK_VALUES[kIndex] * Math.pow(tempR - UK_VALUES[kIndex], 2));
       iFactor  = 2 * rhoR * PK_VALUES[kIndex] * (rhoR - 1);
    }
diffAggregate += (diffSegment * (IK_VALUES[kIndex] - iFactor));
}

Any help would be greatly appreciated! Thank you so much in advance.

任何帮助将不胜感激!非常感谢你提前。

回答by erdekhayser

First, in order for these functions to be available, your code needs to have one of these imports at the top:

首先,为了使这些函数可用,您的代码需要在顶部具有以下导入之一:

import Foundation //Generic
import UIKit      //iOS
import Cocoa      //OS X

The Swift version of Java's Math.powis simply pow(Double, Double). The first parameter is the base, the second is the power.

Java 的 Swift 版本Math.pow只是pow(Double, Double). 第一个参数是基数,第二个参数是功率。

There is no direct substitute for Math.ex, but you can use pow(M_E, 2)to find e^2. M_Eis a defined constant equal to Euler's constant.

没有直接替代品Math.ex,但您可以使用它pow(M_E, 2)来查找 e^2。M_E是等于欧拉常数的定义常数。

Edit: As it turns out, there is an exp(Double)function in Swift. The way I showed above is likely the way it is defined, but I probably should have done more research before saying that. So pow(M_E,2)and exp(2)are both options.

编辑:事实证明,exp(Double)Swift 中有一个函数。我上面展示的方式可能就是它的定义方式,但在说之前我可能应该做更多的研究。所以pow(M_E,2)exp(2)都是选择。