Binary operator '/' cannot be applied to two (Int) operands [duplicate] - xcode

This question already has answers here:
Passing lists from one function to another in Swift
(2 answers)
Closed 7 years ago.
I am getting a Binary operator '/' cannot be applied to two (Int) operands error when I put the following code in a Swift playground in Xcode.
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf()
sumOf(42, 597, 12)
The above was a function calculating the total sum of any numbers.
Below is a function calculating the average of the numbers. The function is calling the sumOf() function from within itself.
func avg(numbers: Int...) -> Float {
var avg:Float = ( sumOf(numbers) ) / ( numbers.count ) //Binary operator '/' cannot be applied to two (Int) operands
return avg
}
avg(1, 2, 3);
Note: I have looked everywhere in stack exchange for the answer, but the questions all are different from mine because mine is involving two Ints, the same type and not different two different types.
I would like it if someone could help me to solve the problem which I have.

Despite the error message it seems that you cannot forward the sequence (...) operator. A single call of sumOf(numbers) within the agv() function gives an error cannot invoke sumOf with an argument of type ((Int))

The error is telling you what to do. If you refer to https://developer.apple.com/library/mac/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_operators.html
/ Division.
A binary arithmetic operator that divides the number to its left by the number to its right.
Class of operands: integer, real
Class of result: real
The second argument has to be real. Convert it like so. I don't use xcode, but I think my syntax is correct.
var avg:Float = ( sumOf(numbers) ) / Float( numbers.count )

Related

Is there a way to use range with Z3ints in z3py?

I'm relatively new to Z3 and experimenting with it in python. I've coded a program which returns the order in which different actions is performed, represented with a number. Z3 returns an integer representing the second the action starts.
Now I want to look at the model and see if there is an instance of time where nothing happens. To do this I made a list with only 0's and I want to change the index at the times where each action is being executed, to 1. For instance, if an action start at the 5th second and takes 8 seconds to be executed, the index 5 to 12 would be set to 1. Doing this with all the actions and then look for 0's in the list would hopefully give me the instances where nothing happens.
The problem is: I would like to write something like this for coding the problem
list_for_check = [0]*total_time
m = s.model()
for action in actions:
for index in range(m.evaluate(action.number) , m.evaluate(action.number) + action.time_it_takes):
list_for_check[index] = 1
But I get the error:
'IntNumRef' object cannot be interpreted as an integer
I've understood that Z3 isn't returning normal ints or bools in their models, but writing
if m.evaluate(action.boolean):
works, so I'm assuming the if is overwritten in a way, but this doesn't seem to be the case with range. So my question is: Is there a way to use range with Z3 ints? Or is there another way to do this?
The problem might also be that action.time_it_takes is an integer and adding a Z3int with a "normal" int doesn't work. (Done in the second part of the range).
I've also tried using int(m.evaluate(action.number)), but it doesn't work.
Thanks in advance :)
When you call evaluate it returns an IntNumRef, which is an internal z3 representation of an integer number inside z3. You need to call as_long() method of it to convert it to a Python number. Here's an example:
from z3 import *
s = Solver()
a = Int('a')
s.add(a > 4);
s.add(a < 7);
if s.check() == sat:
m = s.model()
print("a is %s" % m.evaluate(a))
print("Iterating from a to a+5:")
av = m.evaluate(a).as_long()
for index in range(av, av + 5):
print(index)
When I run this, I get:
a is 5
Iterating from a to a+5:
5
6
7
8
9
which is exactly what you're trying to achieve.
The method as_long() is defined here. Note that there are similar conversion functions from bit-vectors and rationals as well. You can search the z3py api using the interface at: https://z3prover.github.io/api/html/namespacez3py.html

What does this syntax mean (...) [duplicate]

This question already has answers here:
What are these three dots in React doing?
(23 answers)
Closed 4 years ago.
I'm putting my hands into reason-react.
In the following code :
let component = ReasonReact.statelessComponent("Component3");
let make = (~name, _children) => {
...component,
render: self => <input type_="checkbox" />,
};
I don't understand what (...) means on line 3.
When I delete it I get an error message :
The record field component can't be found.
If it's defined in another module or file, bring it into scope by:
- Annotating it with said module name: let baby = {MyModule.age: 3}
- Or specifying its type: let baby: MyModule.person = {age: 3}
The representation is called Spread Syntax. This was introduced in ES6.
Definition and example from MDN Docs. Link at the bottom.
Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers));
// expected output: 6
console.log(sum.apply(null, numbers));
// expected output: 6
More details at : Spread Syntax

How does the Random generator work in elm?

I am having problem understanding how Random generators were suppose to work.
In the following example I'm trying to roll two dices on click,
https://ellie-app.com/d9rXQHpfJa1/1
but 'm getting
Function generate is expecting the 2nd argument to be:
Random.Generator ( Int, Int )
But it is:
( Random.Generator Int, Random.Generator Int )
The error message is giving you a strong hint that you are attempting to pass in a parameter that doesn't fit with what is expected. Elm does a lot of type inference and since NewFace (Int, Int) is a constructor that takes a tuple of two integers, that's what it expects for the second parameter passed to generate.
If you visit the Random package documentation, you'll see a function that takes two generators and gives you back a generator that uses the first two in a tuple. It is called Random.pair, and if you were to use it in your code, it would look like this:
( model, Random.generate NewFace (Random.pair (Random.int 1 6) (Random.int 1 6 )))

Crash when casting the result of arc4random() to Int

I've written a simple Bag class. A Bag is filled with a fixed ratio of Temperature enums. It allows you to grab one at random and automatically refills itself when empty. It looks like this:
class Bag {
var items = Temperature[]()
init () {
refill()
}
func grab()-> Temperature {
if items.isEmpty {
refill()
}
var i = Int(arc4random()) % items.count
return items.removeAtIndex(i)
}
func refill() {
items.append(.Normal)
items.append(.Hot)
items.append(.Hot)
items.append(.Cold)
items.append(.Cold)
}
}
The Temperature enum looks like this:
enum Temperature: Int {
case Normal, Hot, Cold
}
My GameScene:SKScene has a constant instance property bag:Bag. (I've tried with a variable as well.) When I need a new temperature I call bag.grab(), once in didMoveToView and when appropriate in touchesEnded.
Randomly this call crashes on the if items.isEmpty line in Bag.grab(). The error is EXC_BAD_INSTRUCTION. Checking the debugger shows items is size=1 and [0] = (AppName.Temperature) <invalid> (0x10).
Edit Looks like I don't understand the debugger info. Even valid arrays show size=1 and unrelated values for [0] =. So no help there.
I can't get it to crash isolated in a Playground. It's probably something obvious but I'm stumped.
Function arc4random returns an UInt32. If you get a value higher than Int.max, the Int(...) cast will crash.
Using
Int(arc4random_uniform(UInt32(items.count)))
should be a better solution.
(Blame the strange crash messages in the Alpha version...)
I found that the best way to solve this is by using rand() instead of arc4random()
the code, in your case, could be:
var i = Int(rand()) % items.count
This method will generate a random Int value between the given minimum and maximum
func randomInt(min: Int, max:Int) -> Int {
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
The crash that you were experiencing is due to the fact that Swift detected a type inconsistency at runtime.
Since Int != UInt32 you will have to first type cast the input argument of arc4random_uniform before you can compute the random number.
Swift doesn't allow to cast from one integer type to another if the result of the cast doesn't fit. E.g. the following code will work okay:
let x = 32
let y = UInt8(x)
Why? Because 32 is a possible value for an int of type UInt8. But the following code will fail:
let x = 332
let y = UInt8(x)
That's because you cannot assign 332 to an unsigned 8 bit int type, it can only take values 0 to 255 and nothing else.
When you do casts in C, the int is simply truncated, which may be unexpected or undesired, as the programmer may not be aware that truncation may take place. So Swift handles things a bit different here. It will allow such kind of casts as long as no truncation takes place but if there is truncation, you get a runtime exception. If you think truncation is okay, then you must do the truncation yourself to let Swift know that this is intended behavior, otherwise Swift must assume that is accidental behavior.
This is even documented (documentation of UnsignedInteger):
Convert from Swift's widest unsigned integer type,
trapping on overflow.
And what you see is the "overflow trapping", which is poorly done as, of course, one could have made that trap actually explain what's going on.
Assuming that items never has more than 2^32 elements (a bit more than 4 billion), the following code is safe:
var i = Int(arc4random() % UInt32(items.count))
If it can have more than 2^32 elements, you get another problem anyway as then you need a different random number function that produces random numbers beyond 2^32.
This crash is only possible on 32-bit systems. Int changes between 32-bits (Int32) and 64-bits (Int64) depending on the device architecture (see the docs).
UInt32's max is 2^32 − 1. Int64's max is 2^63 − 1, so Int64 can easily handle UInt32.max. However, Int32's max is 2^31 − 1, which means UInt32 can handle numbers greater than Int32 can, and trying to create an Int32 from a number greater than 2^31-1 will create an overflow.
I confirmed this by trying to compile the line Int(UInt32.max). On the simulators and newer devices, this compiles just fine. But I connected my old iPod Touch (32-bit device) and got this compiler error:
Integer overflows when converted from UInt32 to Int
Xcode won't even compile this line for 32-bit devices, which is likely the crash that is happening at runtime. Many of the other answers in this post are good solutions, so I won't add or copy those. I just felt that this question was missing a detailed explanation of what was going on.
This will automatically create a random Int for you:
var i = random() % items.count
i is of Int type, so no conversion necessary!
You can use
Int(rand())
To prevent same random numbers when the app starts, you can call srand()
srand(UInt32(NSDate().timeIntervalSinceReferenceDate))
let randomNumber: Int = Int(rand()) % items.count

Sign of a symbolic algebraic expression

Is there any algorithm that can find the sign of an arbitrary symbolic algebraic expression given in a "Tree - Form"?
I know that a general algorithm doesn't exist because the zero recognizion problem is undecidable for an arbitrary expression, but how should I approach the problem of finding the sign of an expression?
(how is this done in computer algebra?)
For example: sign(sqrt(2)-1) = ?
Evaluate the function value
You need function evaluator engine for that (it is not that hard to code) there is no way to evaluate sign only if you want to support +,- operations !!! All my function evaluators works like this:
compile the source text of the function
First create supported functions table (id,num of operands,name,pointer to function) like:
+,-,*,/,sin,cos,....
These will be the building blocks to any supported expression you need to evaluate. Do not forget to code all functions in your code too. Handle brackets (,) also as functions (push,pop). Group your functions by number of operands so +,- are with 1 and 2 operands (two different functions each !!!).
Now from expression extract:
variable names
constant names and values
number values
Into some kind of table/list:
variables[](id,name,value)
constants[](id,name,value)
numbers [](id, ,value)
And now finally construct compiled function string. My strings are set of two int's. First is type (which table to use) and second is id (index in table).
for example expression:
sign(sqrt(2)-1)
types:
id type
0 function
1 number
2 constant
3 variable
functions:
id name pointer
0 '(' ???
1 ')' ???
2 '+' ???
3 '-' ???
4 '*' ???
5 '/' ???
6 'sqrt' ???
7 'sign' ???
There are no variables or constants. The numbers are:
id value
0 2
1 1
compiled string:
type id
0 7 // sign(1 operand)
0 6 // sqrt(1 operand)
1 0 // 2
0 3 // - (2 operands)
1 1 // 1
After compilation you need to interpret the string and evaluate it's value.
init variables
op1=0`,`op2=0, // set all operands to zero (number depends on supported functions usually 2)
opn=0 // actual operands number
fx=none // actual function (for example none=-1)
fxn=0 // actual function operands number
read first record of compiled string
if it is value (number,constant,variable) set appropriate op? value with it and increment operand counter opn++.
if it is function set fx,fxn code with it
if opn == fxn
You reached needed operand count so execute function fx and init next function
op1=fxtab[fx].pointer(op1,op2,...)
fx=none,fxn=1
opn=1 (some spec functions can return more operands, then set op1,op2,.. opn=...)
if not end of string goto #2 but with next string record
at the end op1 should hold your output value
some example functions (C++ implementation):
double sign(double op1)
{
if (op1>0.0) return +1.0;
if (op1<0.0) return -1.0;
return 0.0;
}
double sqrt1(double op1) { return sqrt(op1); }
double plus1(double op1) { return op1; }
double minus1(double op1) { return -op1; }
double plus2(double op1,double op2) { return op1+op2; }
double minus2(double op1,double op2) { return op1-op2; }
[Notes]
You have to handle special cases like function = "";. Also beware spacing, case sensitivity because any error in compilation invalidates the result.
Speed is not a big issue this is interpreting-evaluation not numerical solution. All operations are called the same times as you would do on the paper.
You should also handle mathematic errors (overflows,invalid operands,NaN,Inf ...)
I usually group functions with the same number of operands to own type to simplify things

Resources