I have a "creative" algorithm I'm working on, and there is a case where I need to return negative Nan.
extension Decimal {
func placement(
between gains: Decimal,
and losses: Decimal
) -> Decimal {
if gains == losses {
return self > gains ? (1 / 0) : (-1 / 0)
}
return (self - losses) / (gains - losses)
}
}
Unfortunately (-1 / 0) produces Nan instead of -Nan.
I've accidentally created -Nan previously, unfortunately, I don't remember how it happened.
When something is literally "not a number", how can it have a meaningful sign?
And, from a practical perspective, how do you expect to distinguish "negative NaN" from "NaN"? Decimal.nan == -Decimal.nan is true, as well as Decimal.nan < 0 and -Decimal.nan < 0
let n = Decimal.nan
let nn = -Decimal.nan
print (n < 0) // true
print (nn < 0) // true
print (nn < n) // false
print (n < nn) // false
print (n == nn) // true
print(-Double.nan) // produces -nan
print(-Decimal.nan) // produces Nan
I think Decimal might not track signed nan. It doesn't distinguish between positive and negative nan but if it is negative nan, isNan will produce true.
Related
I want to perform a big mod (%) operation like the example below:
083123456787654325500479087654 % 55
As you can see this number is bigger than Int64.max (9223372036854775807)
I tried to parse this "083123456787654325500479087654" from string into a Decimal but I can't perform mod operation with two Decimals.
Any suggestions?
You can define a custom mod operator between two decimals such as follow. I haven't the time to test for all scenarios. So I'm selecting the simplest case: modulo between 2 positive numbers. You can expand it to suit your situation:
func % (lhs: Decimal, rhs: Decimal) -> Decimal {
precondition(lhs > 0 && rhs > 0)
if lhs < rhs {
return lhs
} else if lhs == rhs {
return 0
}
var quotient = lhs / rhs
var rounded = Decimal()
NSDecimalRound(&rounded, "ient, 0, .down)
return lhs - (rounded * rhs)
}
let a = Decimal(string: "083123456787654325500479087654")!
print(a % 55)
The result is 49.
I find out a lot of example to solve it, but nothing in SWIFT. Please help
smthng like this
Input : n = 4
Output : Yes
2^2 = 4
Input : n = 7
Output : No
Input : n = 32
Output : Yes
2^5 = 32
I needed algorithm for checking if a number is a power of 2. like 4, 8, 16 , 32 , 64 .... is number power of two
Determining if an integer is a power of 2
from the Bit Twiddling Hacks
is almost verbatim translated to Swift:
func isPowerOfTwo(_ n: Int) -> Bool {
return (n > 0) && (n & (n - 1) == 0)
}
Example:
print(isPowerOfTwo(4)) // true
print(isPowerOfTwo(5)) // false
Or as a generic function, so that it can be used with all binary
integer types:
func isPowerOfTwo<T: BinaryInteger> (_ n: T) -> Bool {
return (n > 0) && (n & (n - 1) == 0)
}
Example:
print(isPowerOfTwo(Int16(4))) // true
print(isPowerOfTwo(UInt8(5))) // false
Or as a protocol extension:
extension BinaryInteger {
var isPowerOfTwo: Bool {
return (self > 0) && (self & (self - 1) == 0)
}
}
Example:
print(1048576.isPowerOfTwo) // true
print(Int(50).isPowerOfTwo) // false
Partial answer:
If it's a FixedWidthInteger and it's positive and its non zero bit count is 1, then it is a power of 2.
let x = 128
if x > 0 && x.nonzeroBitCount == 1
{
// power of 2
}
For a floating point number, I think you can just test the significand. If it is exactly 1, the number is a power of 2.
let x: Double = 4
if x > 0 && x.significand == 1
{
// Power of 2
}
I haven't checked that in a Playground yet, so it might be wrong.
let numberToBeChecked = 4
result = numberToBeChecked.squareRoot()
If result%1 == 0 {
print(“4 is a power of 2”) } else {
print(“4 is not a power of 2”)
}
//note: result%1== 0 checks if result is a whole number.
Hope this works.
Why does the expression DBL_MIN < 0 returns false?
Why do the comparisons against DLB_MIN seem to indicate that DBL_MIN is positive?
let a = DBL_MIN // 2.225073858507201e-308
let b = DBL_MAX // 1.797693134862316e+308
if a < 0.0 {
print("1. DBL_MIN is indeed less than zero") // doesn't print (unexpected)
}
if DBL_MIN < 0.0 {
print("2. DBL_MIN is indeed less than zero") // doesn't print (unexpected)
}
if DBL_MIN > 0.0 {
print("3. DBL_MIN is larger than zero?") // prints (unexpected)
}
if DBL_MIN > DBL_MAX {
print("4. DBL_MIN did some strange flip?") // doesn't print (OK)
}
if b > 0.0 {
print("5. DBL_MAX is indeed larger than zero") // prints (OK)
}
/* printout:
3. DBL_MIN is larger than zero?
5. DBL_MAX is indeed larger than zero */
I suspect it has something to do with floating point precision, but I can't really explain it myself.
I am using Swift 2.1.1 and XCode 7.2.
It is not minimal in the sense that is the largest negative number but the number closest to zero representable as Double:
2.225073858507201 * 10 ^ -308
That simply is a positive value. The - represents a negative exponent, not a negative overall value.
Is there a way to arithmetically simulate 32-bit, twos-complement integer overflow with numbers of a type whose value space is a strict superset of that of the 32-bit twos-complement integers? I need to perform such an operation in, for example, WolframAlpha, which has no explicit typing and no type casting.
The output of my desired convertTo32BitSignedInt(aValue) function needs to be the same as if I had cast the value in a language that supports it, such as Java: (int)aValue.
By example, the output of convertTo32BitSignedInt(17643225600) needs to be 463356416, the same as I had used the following cast (int)17643225600.
For the moment, my convertTo32BitSignedInt function (in pseudo code) looks like this and I am pretty sure it's not the better solution.
if(x > 2147483647 && floor(x / 2147483647 ) == 1){
return (x - 2*2147483648);
}else if(x > 2147483647 && (x % 2147483647 == 0) && (x % 2 == 0)){
return -1 * (x / 2147483647);
}else if(x > 2147483647 && (x % 2147483647 == 0) && (x % 2 > 0)){
return -1 * ((x - 2147483647) / 2147483647) + 2147483647;
}else if(x > 2147483647 && (x % 2147483647 > 0) && (x % 2 == 0)){
return -1 * floor(x / 2147483647) + (x % 2147483647);
}
//...
Use Case:
I try to demonstrate a certain behavior that will occures when there is a 32-bit signed integer overflow in a java program using a recursive implementation of the factorial function.
public int factorial(int n) {
return n == 1 || n==0 ? 1 : n * factorial(n - 1);
}
This int implementation, for factorial(13) gives 1932053504, because 13 * 479001600 > 2147483647, the 32-bit signed integer maximum value.
I use WolframAlpha for the demonstration. WolframAlpha allows numbers > 2147483647 and I want to simulate these number as 32-bit integer numbers. WolframAlpha gives the real answer which is 6227020800. I would like to be able to convert 6227020800 as 1932053504.
Edit: this is a rip & replace of my initial answer
You can do something roughly like this:
convertTo32BitSignedInt(aValue) {
bits32 = BitAnd(aValue, BitShiftLeft(1, 32) - 1);
sign = BitShiftRight(bits32, 31);
return bits32 - BitShiftLeft(sign, 32);
}
any of you knows how can I check if the division remainder is integer or zero?
if ( integer ( 3/2))
You should use the modulo operator like this
// a,b are ints
if ( a % b == 0) {
// remainder 0
} else
{
// b does not divide a evenly
}
It sounds like what you are looking for is the modulo operator %, which will give you the remainder of an operation.
3 % 2 // yields 1
3 % 1 // yields 0
3 % 4 // yields 1
However, if you want to actually perform the division first, you may need something a bit more complex, such as the following:
//Perform the division, then take the remainder modulo 1, which will
//yield any decimal values, which then you can compare to 0 to determine if it is
//an integer
if((a / b) % 1 > 0))
{
//All non-integer values go here
}
else
{
//All integer values go here
}
Walkthrough
(3 / 2) // yields 1.5
1.5 % 1 // yields 0.5
0.5 > 0 // true
swift 3:
if a.truncatingRemainder(dividingBy: b) == 0 {
//All integer values go here
}else{
//All non-integer values go here
}
You can use the below code to know which type of instance it is.
var val = 3/2
var integerType = Mirror(reflecting: val)
if integerType.subjectType == Int.self {
print("Yes, the value is an integer")
}else{
print("No, the value is not an integer")
}
let me know if the above was useful.
Swift 5
if numberOne.isMultiple(of: numberTwo) { ... }
Swift 4 or less
if numberOne % numberTwo == 0 { ... }
Swift 2.0
print(Int(Float(9) % Float(4))) // result 1