Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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.

For example, in 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.

like image 792
Matty Avatar asked Dec 15 '22 16:12

Matty


1 Answers

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.pow is simply pow(Double, Double). The first parameter is the base, the second is the power.

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

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.

like image 95
erdekhayser Avatar answered Dec 31 '22 21:12

erdekhayser