Which is the Swift equivalent of isnan()? - cocoa

Which is the equivalent of isnan() in Swift ?
I need to check if some operation results are valid and delete those invalid like x/0
Thanks

It's defined in the FloatingPointNumber protocol, which both the Float and Double types conform to. Usage is as follows:
let d = 3.0
let isNan = d.isNaN // False
let d = Double.NaN
let isNan = d.isNaN // True
If you're looking for a way to make this check yourself, you can. IEEE defines that NaN != NaN, meaning you can't directly compare NaN to a number to determine its is-a-number-ness. However, you can check that maybeNaN != maybeNaN. If this condition evaluates as true, you're dealing with NaN.
Although you should prefer using aVariable.isNaN to determine if a value is NaN.
As a bit of a side note, if you're less sure about the classification of the value you're working with, you can switch over value of your FloatingPointNumber conforming type's floatingPointClass property.
let noClueWhatThisIs: Double = // ...
switch noClueWhatThisIs.floatingPointClass {
case .SignalingNaN:
print(FloatingPointClassification.SignalingNaN)
case .QuietNaN:
print(FloatingPointClassification.QuietNaN)
case .NegativeInfinity:
print(FloatingPointClassification.NegativeInfinity)
case .NegativeNormal:
print(FloatingPointClassification.NegativeNormal)
case .NegativeSubnormal:
print(FloatingPointClassification.NegativeSubnormal)
case .NegativeZero:
print(FloatingPointClassification.NegativeZero)
case .PositiveZero:
print(FloatingPointClassification.PositiveZero)
case .PositiveSubnormal:
print(FloatingPointClassification.PositiveSubnormal)
case .PositiveNormal:
print(FloatingPointClassification.PositiveNormal)
case .PositiveInfinity:
print(FloatingPointClassification.PositiveInfinity)
}
Its values are declared in the FloatingPointClassification enum.

The accepted answer works but when I first saw it I wasn't exactly clear because of the example and i didn't know that NaN is an acronym for "not a number".
Here's an example from Apple for anyone who isn't clear:
let x = 0.0
let y = x * .infinity // y is a NaN because .infinity is not a number
if y.isNan {
print("this is NaN") // this will print
} else {
print("this isn't Nan")
}

Related

How write a hash function to make such expression to be true?

pseudocode:
// deprecated x!=y && hash(x) == hash(y) // how to make this true?
x!=y && hash(x) == hash(y) && (z!=x && z!=y) && (hash(x) != hash(z) && (hash(y) != hash(z)) // how to make this true?
x and y can be any readable value
Whatever the language, the pseudocode is just help to understand what I mean.
I just wonder how to implement such hash function.
PS: For math, i am an idiot. I can not imagine if there is an algorithm that can do this.
UPDATE 1:
The pseudocode has bug, so I updated the code(actually still has bug, never mind, I will explain).
My original requirement is to make a hash function that can return same value for different parameter, and the parameter value should contains some rule. It means, only the parameter value in same category would gets same hash code, others are not.
e.g.
The following expressions are clearly(you can treat '0' as placeholder):
hash("1.1") == hash("1.0") == hash("0.1")
hash("2.2") == hash("2.0") == hash("0.2")
and
hash("2.2") != hash("2.1") != hash("1.2")
I think this question can do such description:
There are two or more different values contains implied same attribute.
Only these values have such same attribute in the world.
The attribute can obtain through some way(maybe a function), hash() will call it inside.
hash() one of the values, you can retrive the attribute, then you can get the unique hashCode.
It's looks like hash collision, but we exactly know what they are. Also looks like many-to-one model.
How to design collision rules? The values could be any character or numeric. And how to implement the designs?
PPS: This is a question full of bugs, maybe the updated parts cannot explain the the problem either. Or maybe this is a false proposition. I want abstract my issue as a general model, but it makes my mind overflowed. If necessary I will post my actual issue that I am facing.
Any constant hash trivially satisfies your condition:
hash(v) = 42
A less constant answer than yuri kilocheck's would be to use the mod operator:
hash(v) = v % 10;
Then you'll have:
hash(1) = 1
hash(2) = 2
hash(3) = 3
...
hash(11) = 1
hash(12) = 2

Stop Rounding with NSExpression in Calculator [duplicate]

I want to calculate a string, which I'm doing by this:
NSExpression *expression = [NSExpression expressionWithFormat:calculationString];
float result = [[expression expressionValueWithObject:nil context:nil] floatValue];
NSLog(#"%f", result);
The problem is, when calculationstring is 1/2, the result is 0. I tried to change float with double and NSNumber and the %f to %f and %#, but I always just get 0. What to I have to change?
Also if it matters, I am in Europe, so I have commas instead of points for this value, but it shouldn't matter as I am logging with %f which shows it as points. Just for information
Basically, you just need to tell it that you are performing floating point operation,
1.0/2
1.0/2.0
1/2.0
Will all work
Typing in NSExpression is much like in C: literals that look like integers (no decimal point/comma) are treated as integers and thus use integer division. (Under integer division, 1/2 is zero. If you want 0.5, you need floating point division.) This happens when the expression is parsed and evaluated, so attempting to change the type of the result or the formatting of the output has no effect -- those things happen after parsing and evaluation.
If your calculationString is entirely under your control, it's easy to make sure that you use floating point literals anywhere you want floating point division. (That is, use 1.0/2 instead of 1/2.) If not, you'll need to change it such that it does -- here it's probably better to decompose the parsed NSExpression and change an operand rather than munge the string.
Followup edit on the "decompose" bit: String munging in content that you know to have higher-order structure is generally problematic. And with NSExpression, you already have a parser (who's smarter than a simple regex) decomposing the string for you — that is in fact what NSExpression is all about.
So, if you're working with a user-provided string, don't try to change the expression by changing the string. Let NSExpression parse it, then use properties of the resulting object to pick it apart into its constituent expressions. If your string is simply "1/2", then your expression has an array of two arguments and the function "divide:by:" — you can replace it with an equivalent function where one of the arguments is explicitly a floating-point value:
extension NSExpression {
var floatifiedForDivisionIfNeeded: NSExpression {
if function == "divide:by:", let args = arguments, let last = args.last,
let firstValue = args.first?.constantValue as? NSNumber {
let newFirst = NSExpression(forConstantValue: firstValue.doubleValue)
return NSExpression(forFunction: function, arguments: [newFirst, last])
} else {
return self
}
}
}
I think You need to User DDMathParser Which is best in this situation. I have used it in One of my project which is facing same problem as you have faced
DDMathEvaluator *eval = [DDMathEvaluator defaultMathEvaluator];
id value=[eval evaluateString:#"1/2" withSubstitutions:nil error:&error];
NSLog(#"Result %#",value);
Result 0.5
Rickster's solution worked, but had problems with expressions like 5*5/2, where the first argument (here 5*5) was not just a number.
I found a different solution here that works for me: https://stackoverflow.com/a/46554342/6385925
for people who still have this problem i did a somewhat quick fix:
extension String {
var mathExpression: String {
var returnValue = ""
for value in newString.components(separatedBy: " ") {
if value.isOperator {
returnValue += value
} else {
returnValue += "\(Double(value) ?? 0)"
}
}
return returnValue
}
var isOperator: Bool {
["+", "-", "/", "x", "*"].contains(self)
}
}

Range of doubles in Swift

I am currently writing a Swift application and parts of it require making sure certain user inputs add up to a specified value.
A simplified example:
Through program interaction, the user has specified that totalValue = 67 and that turns = 2. This means that in two inputs, the user will have to provide two values that add up to 67.
So lets say on turn 1 the user enters 32, and then on turn 2 he enters 35, this would be valid because 32 + 35 = 67.
This all works fine, but the moment we verge into more than one decimal place, the program cannot add the numbers correctly. For example, if totalValue = 67 and then on turn 1 the user enters 66.95 and then on turn 2 he enters .05 the program will return that this is an error despite the fact that
66.95 + .05 = 67. This problem does not happen with one decimal place or less (something like turn 1 = 55.5 and turn 2 = 11.5 works fine), only for two decimal spots and beyond. I am storing the values as doubles. Thanks in advance
Some example code:
var totalWeights = 67
var input = Double(myTextField.text.bridgeToObjectiveC().doubleValue)
/*Each turn is for a button click*/
/*For turn 1*/
if inputValid == true && turn == 1 && input < totalWeights
{
myArray[0] = input
}
else
{
//show error string
}
/*For turn 2*/
if inputValid == true && turn == 2 && input == (totalWeights - myArray[0])
{
myArray[1] = input
}
else
{
//show error string
}
If you want exact values from floating point then the float/double types will not work, as they are only ever approximations of exact numbers. Look into using the NSDecimalNumber class from within Swift, I'm not sure what the bridging would look like but it should be simple.
Here is an example of how this could work:
var a = 0
for num in numlist {
a += num
}
var result = false
if a == targetnum
result = true
I haven't tested this out, but if numlist is an array of double then it should work for any input that is a valid number.
One problem I just realized is that there is an issue with doing an equals with doubles, as rounding will cause problems for you. I am not going to show it, but if, while reading in the inputs you keep track of how many numbers to the right of the decimal place, then multiply all of the values by that number of tens, so 66.95 * 100 to get it all as an integer, then add, then do the comparison, after multiplying the targetnum by the same value (100).
Unfortunately there is no ideal solution to this. We must use approximation type comparison.
For example, instead of checking:
if val1 == val2
we must try something like:
if val1 > (val2 - .0005) && val1 < (val2 + .0005)

What's the preferred way to encode a "nullable" field in protobuf 2?

I am defining a ProtoBuf message where I want to have a "nullable" field -- i.e., I want to distinguish between the field having a value and not having a value. As a concrete example, let's say I have "x" and "y" fields to record the coordinates of some object. But in some cases, the coordinates are not known. The following definition will not work, because if x or y are unspecified, then they default to zero (which is a valid value):
message MyObject {
optional float x = 1;
optional float y = 2;
}
One option would be to add a boolean field recording whether the corresponding field's value is known or not. I.e.:
message MyObject {
optional bool has_x = 1; // if false, then x is unknown.
optional bool has_y = 2; // if false, then y is unknown.
optional float x = 3; // should only be set if has_x==true.
optional float y = 4; // should only be set if has_y==true.
}
But this imposes some extra book-keeping -- e.g., when I set the x field's value, I must always remember to also set has_x. Another option would be to use a list value, with the convention that the list always has either length 0 or length 1:
message MyObject {
repeated float x = 1; // should be empty or have exactly 1 element.
repeated float y = 2; // should be empty or have exactly 1 element.
}
But in this case, the definition seems a bit misleading, and the interface isn't much better.
Is there a third option that I haven't thought of that's better than these two? How have you dealt with storing nullable fields in protobuf?
Protobuf 2 messages have a built-in notion of "nullable fields". The C++ interface contains methods has_xxx and clear_xxx to check if the field has been set and to unset the field, respectively.
This feature comes "for free" due to the way fields are encoded in message using "tags". An unset field is simply "not present" in the encoded message.
Proto 3 does not have this feature, instead setting any missing field to its default value.
Have a notion of NaN for each of the types and then use default (as shown below) to set it as the value. This will be used if nothing is specified for that particular field.
optional float x = 1 [default = -1];

Concept of true,false logically and numerically?

I was asked this question in an interview! I just wanted to know what the right answer to this is. I told that logically the concept is represented by bool data type(C#).A variable of bool data type can have true or false value and can be used as a conditional check condition.Numerically, 1 represents true and 0 represents false in most programming languages.I don't know what else to add or what is the distinction between the two.Any comments will be greatly appreciated.
In C# (unlike some other languages) booleans are not integers and are not convertible to integers:
int x = true; // Error - Cannot implicitly convert type 'bool' to 'int'
As a result it doesn't make sense to say that true is equal to 1 in C#. At an implementation level the value true might be stored internally as the value 1, but this is a detail specific to that implementation, not a feature of C# itself.
If you want to convert a boolean to the value 0 or 1 you can do this:
int x = isFoo ? 1 : 0;

Resources