How to Cube Root in xcode? - iphone

I've been trying to make a specific calculation in xcode with user defined variables. Here's what I have:
-(IBAction)calculate:(id)sender{
NSString *oneField = self.one.text;
NSString *twoField = self.two.text;
double resultInNum;
double onedouble = [oneField doubleValue];
double twodouble = [twoField doubleValue];
And what I need to do, is cube root the outcome of
(twodouble/onedouble)
I can't quite find away. Any ideas?

Use the pow function from math.h
pow(x, 1.0/3.0)

Swift
Swift has cubic root functions built in. Here are the signatures:
public func cbrt(_: Double) -> Double
public func cbrtf(_: Float) -> Float
The definitions are located in Darwin module on OS X and Glibc module on Linux.

Include math.h and call pow():
pow(twodouble/onedouble,1.0/3);

Don't remember if math comes included but if it doesn't:
#import <math.h>
Then:
pow(twodouble/onedouble,1.0/3.0);
Taking something to 1/n is like taking the nth root. 1/3 is taking the cube root, 1/2 is taking the square root, etc.

Just raise the divided value to the power of 0.33 ?
NSLog(#"%.f", pow(result,0.33) );

Related

How to deal with the lack of `simd_packed_float3` in Swift

There is no simd_packed_float3 type in Swift.
Why it's a problem?
Consider this Metal struct:
struct Test{
packed_float3 x;
float y;
};
First of all, you can't calculate a buffer pointer to address the memory of y, since you can't do this:
MemoryLayout<simd_packed_float3>.size
(Not sure if stride makes sense with packed types, but anyway with simd types it always gives the same length as size on my devices)
You can't use MemoryLayout<simd_float3>.size either, since it will return 16 and not 12 like in architectures available to me for testing.
Second, if you need to write a packed_float3 value of x to the buffer you will need to write the three consecutive floats, but not a single simd type. Again, simd_float3 is not usable since it will write 0 into the forth word corrupting the memory of the next property in the struct (y).
So I've done this:
struct Float_3{
var x: Float
var y: Float
var z: Float
}
typealias simd_packed_float3 = Float_3
It seems to be a functioning solution, but I'm not sure it's not a nasty thing to do...
What problems may I encounter with this approach, and how could I be sure that it won't break on some device that I don't have?
You can define a packed struct in your bridging header:
struct __attribute__((packed)) PackedFloat3 {
float x;
float y;
float z;
};
MemoryLayout<PackedFloat3>.size == 12
MemoryLayout<PackedFloat3>.stride == 12
By the way, simd_float3 is 16 bytes everywhere, simd types have stricter alignment requirements.
You can also typedef it to packed_float3 under #ifndef #ifdef __METAL_VERSION__ to have the same spelling in Swift and MSL.
The reason to do it in bridging header instead of Swift is that you can use the same structs with same spelling in both shaders and Swift.
I'm answering this following the answers I received on the Swift forum.
Turns out that someone in the Metal team at Apple has already thought of this problem and created the MTLPacked types exactly for the types that would have irregular sizes:
MTLPackedFloat3
MTLPackedFloat4x3

Swift Rounding up Double

I am trying to round a double up to a whole number,
var numberOfBottles = totalVolume / volumeEachBottles
for example numberOfBottles = 275.0 / 250.0
that would give me 1.1, I need it to round up to 2
Try:
var numberOfBottles = totalVolume / volumeEachBottles
numberOfBottles.rounded(.up)
or
numberOfBottles.rounded(.down)
There is a built-in global function called ceil which does exactly this:
var numberOfBottles = ceil(totalVolume/volumeEachBottles)
This returns 2, as a Double.
ceil is actually declared in math.h and documented here in the OS X man pages. It is almost certainly more efficient than any other approach.
Even if you need an Int as your final result, I would start by calculating ceil like this, and then using the Int constructor on the result of the ceil calculation.
import Foundation
var numberOfBottles = 275.0 / 250.0
var rounded = ceil(numberOfBottles)
In case you are looking for rounding it to a whole number and use it in the UI then this can be useful. Just add this as the last thing in your file or in a own file:
extension Double {
func roundToInt() -> Int{
return Int(Darwin.round(self))
}
}
And use it like this if you like to have it in a textlabel:
currentTemp.text = "\(weatherData.tempCelsius.roundToInt())"
Or print it as an Int:
print(weatherData.tempCelsius.roundToInt())

Math notation in Objective-C

I'm would like to create a formula I have, into Objective C code.
float loanP = ((interestRate/100/12) *loanAmount) /(1-(1+(interestRate/100/12))^- loanTens)
Is there some notation I should be using for the
^-loanTens
part?
Many Thanks,
-Code
objective C has all the libraries and classes which were in C/C++.
We have some math classes to perform math functions.
import math.h file
which has math functions useful to you.
here you need power operation i think so.
this will be something like this
int a = pow(10,4);
have a look at the available functions in the math.h and make use of it.
Use pow:
float loanP = ((interestRate/100/12) *loanAmount) / pow(1-(1+(interestRate/100/12)), -loanTens);
Use pow function or u can define value of (1+(interestRate/100/12))^- loanTens using your own code.
int value= 1 + (interestRate/100/12);
int total =1;
for(int i =1;i<=loanTens;i++){
total = total*value;
}
float loanP = ((interestRate/100/12) *loanAmount) /(1-(1/total));
or second method:
float loanP = ((interestRate/100/12) *loanAmount) / (1 - 1/(pow((1+(interestRate/100/12)), loanTens)));

NSString - Truncate everything after decimal point in a double

I have a double that I need only the value of everything before the decimal point.
Currently I am using
NSString *level = [NSString stringWithFormat:#"%.1f",doubleLevel];
but when given a value of 9.96, this returns "10". So it is rounding. I need it to return only the "9". (note - when the value is 9.95, it correctly returns the "9" value.)
Any suggestions?
Thank You.
Simply assign the float/double value to a int value.
int intValue = doubleLevel;
Cast that baby as an int.
int castedDouble = doubleLevel;
Anything after the . in the double will be truncated.
9.1239809384 --> 9
123.90454980 --> 123
No rounding, simple truncation.
If you want to keep it as a float:
CGFloat f = 9.99;
f = floorf(f);
there are quite a variety of floor and round implementations.
they have been around since UN*X, and are actually part of those low-level libraries, be they BSD, Posix, or some other variety - you should make yourself familiar with them.
there are different versions for different "depths" of floating point variables.
NSString *level = [NSString stringWithFormat:#"%d",doubleLevel];

Equivalent of CGPoint with integers?

Cheers,
I like strict typing in C. Therefore, I don't want to store a 2D vector of floats if I specifically need integers. Is there an Apple-provided equivalent of CGPoint which stores data as integers?
I've implemented my type Vector2i and its companion function Vector2iMake() à la CGPoint, but something deep in me screams that Apple was there already.
Updating to explain.
I need a datatype that will store coordinates in a board game. These are most definitely integers. Same would be if I were to implement a tile-based turn based strategy, or a tile-based RPG.
(to directly answer the question...)
I am not aware of a "NSIntegerPoint", but it wouldn't be difficult to make one:
struct NSIntegerPoint {
NSInteger x;
NSInteger y;
};
Along with stuff like:
CG_INLINE NSIntegerPoint
NSIntegerPointMake(NSInteger x, NSInteger y)
{
NSIntegerPoint p; p.x = x; p.y = y; return p;
}
CG_INLINE bool
__NSIntegerPointEqualToPoint(NSIntegerPoint point1, NSIntegerPoint point2)
{
return point1.x == point2.x && point1.y == point2.y;
}
#define NSIntegerPointEqualToPoint __NSIntegerPointEqualToPoint
If you happen to be representing your game board as objects stored in non-sparse nested arrays, then you may want to consider subclassing NSIndexPath, or using it directly.
From the class reference:
The NSIndexPath class represents the path to a specific node in a tree of nested array collections. This path is known as an index path.
Each index in an index path represents the index into an array of children from one node in the tree to another, deeper, node.
According to iPhone Application Programming Guide, all provided points are float-based. And when you use them to work with the screen (eventually expecting integers), you should anyway use floats for independence from screen resolution and etc.
You could use int vectors?
http://developer.apple.com/mac/library/documentation/Performance/Conceptual/vecLib/Reference/reference.html#//apple_ref/doc/uid/TP40002498-CH1g-TPXREF103