I want to store duration of time in a Double and need to extract high and low values of Double (hour and minute) for accessing them. I also need to be able to set Double with two Ints (hour and minute).And I got something here now:
extension Double {
func hour() -> Int {
return NSNumber(double: floor(self)).integerValue
}
func minute() -> Int {
return NSNumber(float: Float(Double((self - floor(self)) * 100))).integerValue
}
init(hour: Int, minute: Int) {
self = Double(hour) + ( Double(minute) / 100 )
}
}
And then I've performed some testing with this in my appDelegate's didFinishLaunchingWithOptions:
var time: Double = 18.30
NSLog("Time is \"%f\" - so hours is \"%d\" and minutes is \"%d\".", time, time.hour(), time.minute())
time = Double(hour: 10, minute: 1)
NSLog("Time is \"%f\" - so hours is \"%d\" and minutes is \"%d\".", time, time.hour(), time.minute())
time = Double(hour: 15, minute: 45)
NSLog("Time is \"%f\" - so hours is \"%d\" and minutes is \"%d\".", time, time.hour(), time.minute())
Now, this code works. One might wonder why I convert Double to Float in the minute() function. This is because of an unknown issue that I faced when using Doubles without converting them to Floats before converting these Floats to Ints. If minutes didn't end with 0, one minute was subtracted for unknown reasons.For example, 10:42 returned 10 hours and 41 minutes. But 10:30 was still 10 hours and 30 minutes.Also 10:00 was 10 hours and 0 minutes.
This routine that I posted here seems to be working, but I was just wondering, if I am as efficient as possible... There's more conversion here than what would be needed.So, any improvements?
And does someone know the reason for unknown issue with decremented minute I mentioned?
A binary floating point number such as Double or Float cannot represent the number 10.42 exactly, therefore
multiplying the fractional part by 100 and truncating the result might give 41.
With the conversion to Float you are just "hiding" the problem.
Here is a version that rounds instead of truncating, and is overall a bit simpler. I have adopted the notation of "minute" from your code,
even if it represents 1/100 of an hour and not 1/60.
extension Double {
func hour() -> Int {
return Int(self)
}
func minute() -> Int {
return Int(round(self * 100.0)) % 100
}
init(hour: Int, minute: Int) {
self = Double(hour) + ( Double(minute) / 100 )
}
}
Other possible approaches to solve your problem:
Store the duration as an integer representing the total
number of minutes. E.g. "10:42" would be stored as 10*60 + 42.
Then you have no rounding problems at all.
Use the Foundation
type NSDecimalNumber instead of Double, which can represent
a decimal integer with up to 38 digits exactly.
Related
With Xcode 11.1 if I run a playground with:
pow(10 as Double, -2) // 0.01
I get same output using Float:
pow(10 as Float, -2) // 0.01
But if I try to use the pow(Decimal, Int) as in:
pow(10 as Decimal, -2) // NaN
Does anybody know why?
Is there a better way to deal with positive and negative exponent with pow and Decimal? I need Decimal as they behave as I expect with currency value.
EDIT: I know how to resolve that from math perspective, I'd like to understand why it happens and/or if it can be solved without adding on the cyclomatic complexity of my code (e.g. checking if the exponent is negative and executing 1 / pow)
Well, algebraically, x^(-p) == 1/(x^(p))
So, convert your negative power to a positive power, and then take the reciprocal.
1/pow(10 as Decimal, 2) // 0.01
I think that this struct give us an idea about the problem:
public struct Decimal {
public var _exponent: Int32
public var _length: UInt32 // length == 0 && isNegative -> NaN
public var _isNegative: UInt32
public var _isCompact: UInt32
public var _reserved: UInt32
public var _mantissa: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16)
public init()
public init(_exponent: Int32, _length: UInt32, _isNegative: UInt32, _isCompact: UInt32, _reserved: UInt32, _mantissa: (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16))
}
The length condition should be satisfacted only length == 0, but as UInt32 doesn't represents fractionary numbers the condition is satisfacted...
That's simply how NSDecimal / NSDecimalNumber works: it doesn't do negative exponents. You can see a rather elaborate workaround described here:
https://stackoverflow.com/a/12095004/341994
As you can see, the workaround is exactly what you've already been told: look to see if the exponent would be negative and, if so, take the inverse of the positive root.
... if it can be solved without adding on the cyclomatic complexity of my code ...
extension Decimal {
func pow(i: Int)->Decimal {
i < 0 ? 1.0 / Foundation.pow(self, -i) : Foundation.pow(self, i)
}
}
it is really not so complex to use it, from your example ....
(10 as Decimal).pow(i: -2) // 0.01
Kindly find my point of view for this Apple function implementation, Note the following examples:
pow(1 as Decimal, -2) // 1; (1 ^ Any number) = 1
pow(10 as Decimal, -2) // NAN
pow(0.1 as Decimal, -2) // 100
pow(0.01 as Decimal, -2) // 10000
pow(1.5 as Decimal, -2) // NAN
pow(0.5 as Decimal, -2) // NAN
It seems like, pow with decimal don't consider any floating numbers except for 10 basis. So It deals with:
0.1 ^ -2 == (1/10) ^ -2 == 10 ^ 2 // It calculates it appropriately, It's 10 basis 10, 100, 1000, ...
1.5 ^ -2 == (3/2) ^ -2 // (3/2) is a floating number ,so deal with it as Double not decimal, It returns NAN.
0.5 ^ -2 == (1/2) ^ -2 // (2) isn't 10 basis, So It will be dealt as (1/2) as It is, It's a floating number also. It returns NAN.
I think this could be a bug on Swift's compiler.
EDIT: This is a weird behaviour on Objective-C's NSDecimalNumber, see #matt's comment on this answer below.
As stated by #jawadAli on his answer
Well, algebraically, x^(-p) == 1/(x^(p))
This formula is correct therefore the following statements should be equal
let ten: Decimal = 10
let one: Decimal = 1
let answer: Decimal = 0.01
pow(ten, -2) // NaN
one / pow(ten, 2) // 0.01
one / (ten * ten) // 0.01
answer // 0.01
Trying this with other data types would result to 0.01.
I also tried to replicate this by using other negative exponents on Decimal data type and it seems to always evaluate to NaN. With the exceptions of 1, 0, and -1
(1...100).forEach {
print(pow(-2, -$0)) // NaN
print(pow(-1, -$0)) // Correct
print(pow(0, -$0)) // Correct
print(pow(-1, -$0)) // Correct
print(pow(-2, -$0)) // NaN
}
I would suggest that you use a different Data Type for now.
I get the following error when using code for an extension, I'm not sure if they're asking to just use a different operator or modify the values in the expression based on an internet search.
Error: % is unavailable: Use truncatingRemainder instead
Extension code:
extension CMTime {
var durationText:String {
let totalSeconds = CMTimeGetSeconds(self)
let hours:Int = Int(totalSeconds / 3600)
let minutes:Int = Int(totalSeconds % 3600 / 60)
let seconds:Int = Int(totalSeconds % 60)
if hours > 0 {
return String(format: "%i:%02i:%02i", hours, minutes, seconds)
} else {
return String(format: "%02i:%02i", minutes, seconds)
}
}
}
The error(s) occur when setting the minutes and seconds variables.
CMTimeGetSeconds() returns a floating point number (Float64 aka
Double). In Swift 2 you could compute the
remainder of a floating point division as
let rem = 2.5 % 1.1
print(rem) // 0.3
In Swift 3 this is done with
let rem = 2.5.truncatingRemainder(dividingBy: 1.1)
print(rem) // 0.3
Applied to your code:
let totalSeconds = CMTimeGetSeconds(self)
let hours = Int(totalSeconds / 3600)
let minutes = Int((totalSeconds.truncatingRemainder(dividingBy: 3600)) / 60)
let seconds = Int(totalSeconds.truncatingRemainder(dividingBy: 60))
However, in this particular case it is easier to convert the duration
to an integer in the first place:
let totalSeconds = Int(CMTimeGetSeconds(self)) // Truncate to integer
// Or:
let totalSeconds = lrint(CMTimeGetSeconds(self)) // Round to nearest integer
Then the next lines simplify to
let hours = totalSeconds / 3600
let minutes = (totalSeconds % 3600) / 60
let seconds = totalSeconds % 60
The % modulus operator is defined only for integer types. For floating-point types, you need to be more specific about the kind of IEEE 754 division/remainder behavior you want, so you have to call a method: either remainder or truncatingRemainder. (If you're doing floating-point math you actually need to care about this, and lots of other stuff, or you can get unexpected / bad results.)
If you actually intend to do integer modulus, you need to convert the return value of CMTimeGetSeconds to an integer before using %. (Note that if you do, you'll lop off the fractional seconds... depending on where you're using CMTime that may be important. Do you want minutes:seconds:frames, for example?)
Depending on how you want to present CMTime values in your UI, it might be better to extract the seconds value and pass it to NSDateFormatter or NSDateComponentsFormatter so you get appropriate locale support.
Bring back the simple modulo syntax in swift 3:
This syntax was actually suggested on Apples official swift mailing list here but for some reason they opted for a less elegant syntax.
infix operator %%/*<--infix operator is required for custom infix char combos*/
/**
* Brings back simple modulo syntax (was removed in swift 3)
* Calculates the remainder of expression1 divided by expression2
* The sign of the modulo result matches the sign of the dividend (the first number). For example, -4 % 3 and -4 % -3 both evaluate to -1
* EXAMPLE:
* print(12 %% 5) // 2
* print(4.3 %% 2.1) // 0.0999999999999996
* print(4 %% 4) // 0
* NOTE: The first print returns 2, rather than 12/5 or 2.4, because the modulo (%) operator returns only the remainder. The second trace returns 0.0999999999999996 instead of the expected 0.1 because of the limitations of floating-point accuracy in binary computing.
* NOTE: Int's can still use single %
* NOTE: there is also .remainder which supports returning negatives as oppose to truncatingRemainder (aka the old %) which returns only positive.
*/
public func %% (left:CGFloat, right:CGFloat) -> CGFloat {
return left.truncatingRemainder(dividingBy: right)
}
This simple swift 3 migration tip is part of a more comprehensive swift 3 migration guide with many insights (35k loc / 8-days of migration) http://eon.codes/blog/2017/01/12/swift-3-migration/
There's no need to create a separate modulo operator for floating point numbers, unless you think it makes the code safer. You can overload the % operator to accept floating point numbers like so:
func %<N: BinaryFloatingPoint>(lhs: N, rhs: N) -> N {
lhs.truncatingRemainder(dividingBy: rhs)
}
Usage
let a: Float80 = 10
let b: Float80 = 3
print(a % b)
You can now use % with any two floating point numbers of the same tye.
I found that the following works in Swift 3:
let minutes = Int(floor(totalSeconds / 60))
let seconds = Int(totalSeconds) % 60
where totalSeconds is a TimeInterval (Double).
I'm attempting to convert MPH into minute miles. I'm currently running code to do this by doing 60 / the miles per hour which gives me the result in minute miles.
For example 60/8mph = 7.5
However the answer I get I need to convert into minutes and seconds so that I would have 7 minutes 30 seconds. Is there a way I can get the numbers after the decimal point so I can multiply it by 60 to convert it to seconds, then add it back to the minutes.
You can use remainder,
double remainder = fmod(a_double, another_double);
should include <math.h>
Well, I don't know whether there is an existing class that handles this, but to answer your specific question, the fractional part of the decimal (mantissa?) would be:
((60 % 8) / 8.0f)
You can multiply that by 60.
Do it in seconds...
3600/8 = 450
450/60 = 7 remainder 30
= 7:30
It's pretty simple, you're on the right path actually.
What you need to do is:
Get Minutes
Get Seconds
Convert seconds from int to real time (0.5 to 30, etc..)
Add seconds to minutes
Get minutes by casting it to an Integer:
int minutes = 60/8;
Get seconds by using the remainder:
float seconds = 60%8;
Convert seconds to real time:
int realSeconds = seconds * 60;
Now get result back by adding both:
int totalSeconds = minuts + realSeconds;
Here's a little function that does it (typed directly to browser, probably won't compile)
#include <math.h>
int getMinuteMiles(float mph){
int minutes = 60/mph;
double seconds = fmod(60, mph);
int realSeconds = seconds * 60;
return minutes+realSeconds;
}
I need to round a number, let's say 543 to either the hundreds or the tens place. It could be either one, as it's part of a game and this stage can ask you to do one or the other.
So for example, it could ask, "Round number to nearest tens", and if the number was 543, they would have to enter in 540.
However, I don't see a function that you can specify target place value to round at. I know there's an easy solution, I just can't think of one right now.
From what I see, the round function rounds the last decimal place?
Thanks
To rounding to 100's place
NSInteger num=543;
NSInteger deci=num%100;//43
if(deci>49){
num=num-deci+100;//543-43+100 =600
}
else{
num=num-deci;//543-43=500
}
To round to 10's place
NSInteger num=543;
NSInteger deci=num%10;//3
if(deci>4){
num=num-deci+100;//543-3+10 =550
}
else{
num=num-deci;//543-3=540
}
EDIT:
Tried to merge the above in one:
NSInteger num=543;
NSInteger place=100; //rounding factor, 10 or 100 or even more.
NSInteger condition=place/2;
NSInteger deci=num%place;//43
if(deci>=condition){
num=num-deci+place;//543-43+100 =600.
}
else{
num=num-deci;//543-43=500
}
You may just use an algorithm in your code:
For example, lets say that you need to round up a number to hundred's place.
int c = 543
int k = c % 100
if k > 50
c = (c - k) + 100
else
c = c - k
To round numbers, you can use the modulus operator, %.
The modulus operator gives you the remainder after division.
So 543 % 10 = 3, and 543 % 100 = 43.
Example:
int place = 10;
int numToRound=543;
// Remainder is 3
int remainder = numToRound%place;
if(remainder>(place/2)) {
// Called if remainder is greater than 5. In this case, it is 3, so this line won't be called.
// Subtract the remainder, and round up by 10.
numToRound=(numToRound-remainder)+place;
}
else {
// Called if remainder is less than 5. In this case, 3 < 5, so it will be called.
// Subtract the remainder, leaving 540
numToRound=(numToRound-remainder);
}
// numToRound will output as 540
NSLog(#"%i", numToRound);
Edit: My original answer was submitted before it was ready, because I accidentally hit a key to submit it. Oops.
Can I set a range of numbers when using arc4random()? For example 50-100 only.
As pointed out in other posts below, it is better to use arc4random_uniform. (When this answer was originally written, arc4random_uniform was not available). Besides avoiding the modulo bias of arc4random() % x, it also avoids a seeding problem with arc4random when used recursively in short timeframes.
arc4random_uniform(4)
will generate 0, 1, 2 or 3. Thus you could use:
arc4random_uniform(51)
and merely add 50 to the result to get a range between 50 & 100 (inclusive).
To expand upon JohnK comment.
It is suggested that you use the following function to return a ranged random number:
arc4random_uniform(51)
which will return a random number in the range 0 to 50.
Then you can add your lower bounds to this like:
arc4random_uniform(51) + 50
which will return a random number in the range 50 to 100.
The reason we use arc4random_uniform(51) over arc4random() % 51 is to avoid the modulo bias. This is highlighted in the man page as follows:
arc4random_uniform(upper_bound) will return a uniformly distributed random number less than upper_bound. arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids "modulo bias" when the upper bound is not a power of two.
In short you get a more evenly distributed random number generated.
int fromNumber = 10;
int toNumber = 30;
int randomNumber = (arc4random()%(toNumber-fromNumber))+fromNumber;
Will generate randon number between 10 and 30, i.e. 11,12,13,14......29
You can use this code for generating random values with range:
//range from 50 to 100
int num1 = (arc4random() % 50) + 50; or
int num1 = arc4random_uniform(50) + 50;
//range from 0-100
int num1 = arc4random() % 100; or
int num1 = arc4random_uniform(100);
In Swift you can use this (inspired by answer of #Justyn)
func generateRandomKey(fromRange rangeFrom:Int, toRange rangeTo:Int) -> Int{
let theKey = arc4random_uniform(UInt32(rangeTo - rangeFrom)) + UInt32(rangeFrom)
return Int(theKey)
}
Will always give you a random range Integer.
In many situations 10 thru 30 would mean inclusive, (includes 10 and 30) ...
int fromNumber = 10;
int toNumber = 30;
toNumber ++;
int randomNumber = (arc4random()%(toNumber-fromNumber))+fromNumber;
Notice the difference toNumber - fromNumber is now 21 ... (20+1) which yields the possible results of 0 thru 20 (inclusive) which when added to fromNumber (10) results in 10 thru 30 (inclusive).