convert centimeter to feet and inches and vice versa different output? - objective-c

I am using following code to convert centimeters into feet and inches but it doesn't work as expected.
+ (NSString*)getfeetAndInches:(float)centimeter {
float totalHeight = centimeter * 0.032808;
float myFeet = (int)totalHeight; //returns 5 feet
float myInches = fabsf((totalHeight - myFeet) * 12);
NSLog(#"%f",myInches);
return [NSString stringWithFormat:#"%d' %0.0f\"",(int)myFeet,roundf(myInches)];
}
I'm using the following code to convert feet and inches string into centimeter
NSInteger totalInches = ([self.Feets integerValue] * 12) + [self.Inches integerValue];
self.heightInCm = totalInches * 2.54;
But when I convert self.heightInCm back to feet and inches it does not provide correct value.Could someone post a perfect working example of this

In general, your code works correctly. There are some minor issues, e.g. the fabsf is not necessary but from my testing it works well.
The problem you have is probably caused by the fact, that when converting to feets and inches, you are rounding off values.
An inch is equal to 2.54 cm. If you are rounding inches to an integer value, your maximum precision will be 2.54 cm.
For example, 5'11' is 180,3 cm. 6'0 is 182,8cm. Anything between those two values (e.g. 181, 182, 183 will get rounded to either 5'11 or 6'0).
The correct solution depends on your use case. If you are only presenting the values to the user, keep them in centimeters and only convert to feet&inches when displaying. If your users are entering the value, you can't make it more precise but you can accept/display inches as a decimal value (replace roundf(myInches) with just myInches and use [self.inches floatValue]).
From the comments, you also have a rounding problem when inches calculated as 11.8 are rounded up to 12 which doesn't make sense in the result. I recommend to rework the algorithm into the following:
const float INCH_IN_CM = 2.54;
NSInteger numInches = (NSInteger) roundf(centimeter / INCH_IN_CM);
NSInteger feet = numInches / 12;
NSInteger inches = numInches % 12;
return [NSString stringWithFormat:#"%#' %#\"", #(feet), #(inches)];
That will easily solve the 12 inch problem because the round is applied to the total length in inches.

This is the Swift version, to convert centimeters to feet and inches:
SWIFT 4
func showFootAndInchesFromCm(_ cms: Double) -> String {
let feet = cms * 0.0328084
let feetShow = Int(floor(feet))
let feetRest: Double = ((feet * 100).truncatingRemainder(dividingBy: 100) / 100)
let inches = Int(floor(feetRest * 12))
return "\(feetShow)' \(inches)\""
}

Related

Objective-C Trigonometry

I'm having a pain with trig at the moment.
double angle = tan(opposite/adjacent);
angle = (angle) * (180.0 / M_PI);
That finds the angle for them particulars, we'll say in this case it equals 15.18º after being converted from radians.
Then, to find the adjacent and opposite of the new Hypotenuse with the same angle I do..
double oppAngle = sin(angle);
double adjAngle = cos(angle);
double secondOpposite = newDistance * oppAngle;
double secondAdjacent = newDistance * adjAngle;
NSLog(#"opposite = %.2f * %.2f = %.2f", oppAngle, newDistance, secondOpposite);
NSLog(#"Adjacent = %.2f * %.2f = %.2f", adjAngle, newDistance, secondAdjacent);
That logs,
2015-06-27 17:36:14.565 opposite = -0.51 * 183.27 = -92.94
2015-06-27 17:36:14.565 Adjacent = -0.86 * 183.27 = -157.95
Which is obviously wrong, as the sine and cosine of them angles are incorrect. The angle logs 15.18º so I'm not too sure where I'm going wrong, unless.. They are converted into radians again? I'm not quite sure where I'm going wrong, however.. It's wrong.
The trig formula is
tan(angle) = opposite / adjacent
So to get the angle from the side lengths, you need to use the inverse tangent, which is atan2.
double angle = atan2(opposite, adjacent);
From there the rest of your code works as long as you know that atan2 returns an angle in radians (so your second line is unnecessary).

Rounding a float number in objective-c

I want to know if there is a simple function that I can use such this sample.
I have a
float value = 1.12345;
I want to round it with calling something like
float value2 = [roundFloat value:value decimal:3];
NSLog(#"value2 = %f", value2);
And I get "1.123"
Is there any Library or default function for that or I should write a code block for this type of calculations?
thank for your help in advance
Using NSLog(#"%f", theFloat) always outputs six decimals, for example:
float theFloat = 1;
NSLog(#"%f",theFloat);
Output:
1.000000
In other words, you will never get 1.123 by using NSLog(#"%f", theFloat).
Cut-off after three decimals:
float theFloat = 1.23456;
float newFLoat = (int)(theFloat * 1000.0) / 1000.0;
NSLog(#"%f",newFLoat);
Output:
1.234000
Round to three decimals (using roundf() / lroundf() / ceil() / floor()):
float theFloat = 1.23456;
float newFLoat = (int)(roundf(theFloat * 1000.0)) / 1000.0;
NSLog(#"%f",newFLoat);
Output:
1.235000
Round to three decimals (dirty way):
float theFloat = 1.23456;
NSString *theString = [NSString stringWithFormat:#"%.3f", theFloat];
float newFloat = [theString floatValue];
NSLog(#"%#",theString);
NSLog(#"%f",newFloat);
Output:
1.235
1.235000
For printing the value use:
NSLog(#"value2 = %.3f", value2);
Rounding to 3 decimal digits before calculations doesn't really make sense because float is not a precise number. Even if you round it to 1.123, it will be something like 1.122999999998.
Rules:
Usually you round up only to print the result - string formatter can handle it (see above).
For precise calculations (e.g. currency), don't use floating point, use NSDecimalNumber or fixed point arithmetics.
Floating point numbers don't have decimal places, they have binary places. Decimal-radix numbers have decimal places. You can't round floating point numbers to specific numbers of decimal places unless you convert to a decimal radix. No routine, method, function etc., that returns a floating point value can possibly carry out this task.
Note that "Round" is not necessarily as simple a topic as you think. For example
DIY Calculator: Rounding Algorithms 101 lists 16 different methods for rounding a number.
Wikipedia:Rounding covers a lot of the same ground
And Cplusplus has source code for a bunch of Rounding Algorithms that are easy translatable to objective-c
How you want to round will depend on the context of what you are doing with for data.
And I should point out that Stack Overflow already has a plethora of other questions about rounding in objective-c
//Your Number to Round (can be predefined or whatever you need it to be)
float numberToRound = 1.12345;
float min = ([ [[NSString alloc]initWithFormat:#"%.0f",numberToRound] floatValue]);
float max = min + 1;
float maxdif = max - numberToRound;
if (maxdif > .5) {
numberToRound = min;
}else{
numberToRound = max;
}
//numberToRound will now equal it's closest whole number (in this case, it's 1)
Here is a simple way to do it:
float numberToRound = 1.12345f;
float remainder = numberToRound*1000.0f - (float)((int)(numberToRound*1000.0f));
if (remainder >= 0.5f) {
numberToRound = (float)((int)(numberToRound*1000.0f) + 1)/1000.0f;
}
else {
numberToRound = (float)((int)(numberToRound*1000.0f))/1000.0f;
}
For an arbitrary decimal place, substitute 1000.0f in the above code with
float mult = powf(10.0f, decimal);
try
#import <math.h>
float cutFloat( float number, int decimal) {
number = number*( pow(10,decimal) );
number = (int)number;
number = number/( pow(10,decimal) ) ;
return number;
}

NSPoint offset by pixels toward angle?

Let me just start with the code.
- (NSPoint*) pointFromPoint:(NSPoint*)point withDistance:(float)distance towardAngle:(float)angle; {
float newX = distance * cos(angle);
float newY = distance * sin(angle);
NSPoint * anNSPoint;
anNSPoint.x = newX;
anNSPoint.y = newY;
return thePoint;
}
This should, based on my knowledge, be perfect. It should return and x value of 0 and a y value of 2 if I call this code.
somePoint = [NSPoint pointFromPoint:somePoint withDistance:2 towardAngle:90];
Instead, I get and x value of 1.05 and a y of 1.70. How can I find the x and y coordinates based on an angle and a distance?
Additional note: I have looked on math.stackexchange.com, but the formulas there led me to this. I need the code, not the normal math because I know I will probably screw this up.
A working version of your function, which accepts values in degrees instead of radians, would look like this:
- (NSPoint)pointFromPoint:(NSPoint)origin withDistance:(float)distance towardAngle:(float)angle
{
double radAngle = angle * M_PI / 180.0;
return NSMakePoint(origin.x + distance * cos(radAngle), point.y + distance * sin(radAngle));
}
Your problem is you're giving the angle in degrees (e.g. 90), but the math is expecting it in radians. Try replacing the 90 with M_PI_2

Rounding an Objective-C float to the nearest .05

I want to round the following floating point numbers to the nearest 0.05.
449.263824 --> 449.25
390.928070 --> 390.90
390.878082 --> 390.85
How can I accomplish that?
The match the output in your question, you can do the following:
float customRounding(float value) {
const float roundingValue = 0.05;
int mulitpler = floor(value / roundingValue);
return mulitpler * roundingValue;
}
Example:
NSLog(#"Output: %f --> %.2f", 449.263824, customRounding(449.263824));
There's the round() function. I think you need to do this:
double rounded = round(number * 20.0) / 20.0;
As with all floating point operations, since 1/5 is not directly representable as a binary value, you'll see bizarre not quite exact results. If you don't like that, you can use NSDecimalNumber's -decimalNumberByRoundingAccordingToBehaviour: method but it'll be a bit slower.
I know the question is answered but I used the following code:
float unrounded = 2.234;
float decimal = 0.05;
float decimal2 = 1/decimal;
float rounded = (((int)((unrounded*decimal2)+0.5))/decimal2);
For example:
> unrounded = 2.234
> decimal = 0.05
> decimal2 = 1/0.05 = 20
>
> rounded:
> 2.234 * 20 = 44.68
> 44.68 + 0.5 = 45.18
> make an integer: 45
> 45 / 20 = 2.25
You could use an NSNumberFormatter to carry out rounding and indeed to specify the rounding you require via one of the NSNumberFormatterRoundingMode options. (Search for "NSNumberFormatterRoundingMode" in the above class reference to see the defaults.)
However, as #Jesse states in the comment on your question, there doesn't seems to be any standard form of rounding going on in the examples you're provided.
If it were round to the nearest x, then you could go with:
roundedValue = originalValue + x * 0.5;
roundedValue -= fmodf(roundedValue, x);
As it is, it isn't entirely clear what you want.
Use floor:
#include <math.h>
...
double result = floor(number * 20.0) / 20.0;

How to create a random float in Objective-C?

I'm trying to create a random float between 0.15 and 0.3 in Objective-C. The following code always returns 1:
int randn = (random() % 15)+15;
float pscale = (float)randn / 100;
What am I doing wrong?
Here is a function
- (float)randomFloatBetween:(float)smallNumber and:(float)bigNumber {
float diff = bigNumber - smallNumber;
return (((float) (arc4random() % ((unsigned)RAND_MAX + 1)) / RAND_MAX) * diff) + smallNumber;
}
Try this:
(float)rand() / RAND_MAX
Or to get one between 0 and 5:
float randomNum = ((float)rand() / RAND_MAX) * 5;
Several ways to do the same thing.
use arc4random() or seed your random values
try
float pscale = ((float)randn) / 100.0f;
Your code works for me, it produces a random number between 0.15 and 0.3 (provided I seed with srandom()). Have you called srandom() before the first call to random()? You will need to provide srandom() with some entropic value (a lot of people just use srandom(time(NULL))).
For more serious random number generation, have a look into arc4random, which is used for cryptographic purposes. This random number function also returns an integer type, so you will still need to cast the result to a floating point type.
Easiest.
+ (float)randomNumberBetween:(float)min maxNumber:(float)max
{
return min + arc4random_uniform(max - min + 1);
}
Using srandom() and rand() is unsafe when you need true randomizing with some float salt.
On MAC_10_7, IPHONE_4_3 and higher you can use arc4random_uniform(upper_bound)*.
It allows to generate true random integer from zero to *upper_bound*.
So you can try the following
u_int32_t upper_bound = <some big enough integer>;
float r = 0.3 * (0.5 + arc4random_uniform(upper_bound)*1.0/upper_bound/2);
To add to #Caladain's answer, if you want the solution to be as easy to use as rand(), you can define these:
#define randf() ((CGFloat)rand() / RAND_MAX)
#define randf_scaled(scale) (((CGFloat)rand() / RAND_MAX) * scale)
Feel free to replace CGFloat with double if you don't have access to CoreGraphics.
I ended up generating to integers one for the actual integer and then an integer for the decimal. Then I join them in a string then I parse it to a floatvalue with the "floatValue" function... I couldn't find a better way and this works for my intentions, hope it helps :)
int integervalue = arc4random() % 2;
int decimalvalue = arc4random() % 9;
NSString *floatString = [NSString stringWithFormat:#"%d.%d",integervalue,decimalvalue];
float randomFloat = [floatString floatValue];