diffrent return value for same arguement of ceil() function - c++17

#include<bits/stdc++.h>
using namespace std;
int main() {
int ans = ceil(1.5);
printf("%d\n", ans);
ans = ceil(3 / 2);
printf("%d", ans);
}
Output:
2
1
Why this code print different answers in my editor (vs code)?

Actually your are sending different arguments to function ceil
3 / 2 will be first calculated to integer 1, for 3 and 2 are all integers so the operator / will return an integer.
So you are actually calling ceil(1) for the second time

When u sent 3/2 as an argument, you are actually sent 1. The program calculates 3/2 as an int therefore the result is 1, and then the second ans calculation is actually by ceil(1.0)
Instead ceil(3 / 2), you need to do ceil(3.0 / 2.0). In this situation, the program calculates this as a double and the result will be 1.5, meaning the second ans calculation is by ceil(1.5).

Related

Multiplying a vector component with an array in ArrayFire

I'm getting an error while trying to multiply a vector component with an array (element-wise multiplication or broadcast). The docs show that this overloaded case for * should be fine:
AFAPI array operator* (const float &lhs, const array &rhs)
Multiplies two arrays or an array and a value. (const array&, const
array&)
But according to the error message below, perhaps vect(0) needs to be further flattened or reduced so that the sizes are consistent?
The error statement is clear:
Invalid dimension for argument 1 Expected: ldims == rides
Below is the code:
#include <arrayfire.h>
int main(int argc, char *argv[])
{
int device = argc > 1 ? atoi(argv[1]) : 0;
af::setDevice(device);
af::info();
int n = 3;
int N = 5;
// Create the arrays:
af::array matrix = af::constant(0,n,n,f32); // 3 x 3 float array of zeros
af::array vect = af::seq(1,N); // A col vector of floats: {1.0, ... ,5.0}
// Show the arrays:
af_print(matrix);
af_print(vect);
// Print a single component of the vector:
af_print(vect(0));
// This line produces the error (see below):
af_print(vect(0) * matrix); // Why doesn't this work?
// But somthing like this is fine:
af_print(1.0 * matrix);
return 0;
}
Producing the output:
ArrayFire v3.3.2
ATI Radeon HD 6750M
matrix [3 3 1 1]
0.0000 0.0000 0.0000
0.0000 0.0000 0.0000
0.0000 0.0000 0.0000
vect [5 1 1 1]
1.0000
2.0000
3.0000
4.0000
5.0000
vect(0) [1 1 1 1]
1.0000
The dims() output of af_print() for the matrix = [3 3 1 1], and vect(0) = [1 1 1 1], make me suspicious, but I'm not sure how to flatten further. One would think this example to be a common way of using the ArrayFire API.
The error exception that is thrown is:
libc++abi.dylib: terminating with uncaught exception of type
af::exception: ArrayFire Exception (Invalid input size:203): In
function getOutDims In file src/backend/ArrayInfo.cpp:173
Invalid dimension for argument 1 Expected: ldims == rides
In function af::array af::operator*(const af::array &, const af::array
&)
Adding a use-case to clarify:
In practice I am constructing a final array by summation of coeff(k) * (a 2-d slice of a 3-d array Z):
for (int j = 0; j<indx.dims(0); ++j)
final += coeff(indx(j)) * Z(af::span,af::span,indx(j));
I'll look into using a gfor but initially just wanted to get the correct numerical output. Note also that the vector: index is predefined, e.g., say index = {1, 2, 4, 7, ...} and the elements are not necessarily in sequence; this allows the selection of specific terms.
ArrayFire does not implicitly do vector array-scalar array element-wise operation (the case you say is failing). Only vector array-value ones are supported implicitly.
To do what you are doing, you will need to use the tile() function as shown below.
af_print(tile(vect(0), matrix.dims()) * matrix);
Since the dimension being tiled is 1, tile will be used as a JIT function. There is no extra memory used here. The entire computation is done in a single kernel. Hence no performance hit either.
Since OP added a usecase since the last answer, this is how you write a fully vectorized version in arrayfire.
array coeffs = moddims(coeff(indx), 1, 1, coeff.elements());
array final = sum(Z(span, span, indx) * tile(coeffs, Z.dims(0), Z.dims(1)), 2);

Swift Range Operator with two unknown values

If I have two unknown values, lets say x and y, what is the best way loop through all of the values between between those values?
For example, given the values x = 0 and y = 5 I would like to do something with the values 0, 1, 2, 3, 4, and 5. The result could exclude 0 and 5 if this is simpler.
Using Swift's Range operator, I could do something like this:
for i in x...y {
// Do something with i
}
Except I do not know if x or y is the greater value.
The Swift documentation for Range Operators states:
The closed range operator (a...b) defines a range that runs from a to b, and includes the values a and b. The value of a must not be greater than b.
There are a number of solutions here. A pretty straight forward one is:
let diff = y - x
for i in 0...abs(diff) {
let value = min(x, y) + i
// Do something with value
}
Is there a better, or more elegant way to achieve this?
I guess the most explicit way of writing it would be:
for i in min(a, b)...max(a, b) {
// Do something with i
}
To exclude the first and last value, you can increment your lower limit and use the Swift ..< syntax:
let lowerLimit = min(a, b) + 1
let upperLimit = max(a, b)
for i in lowerLimit..<upperLimit {
// Do something with i
}

arc4random() gives negative Number in iOS

Sometime arc4random() gives negative number also in objective C.
My code is as follow:
Try 1:
long ii = arc4random();
Try 2:
int i = arc4random();
How can I only get positivite random number?
Thank you,
No, it's always positive as it returns an unsigned 32-bit integer (manpage):
u_int32_t arc4random(void);
You are treating it as a signed integer, which is incorrect.
You should use the arc4random_uniform() function. this is the most common random function used.
arc4random_uniform() function
Returns a random number between 0 and the inserted parameter minus 1.
For example arc4random_uniform(3) may return 0, 1 or 2 but not 3.
Example
u_int32_t randomPositiveNo = arc4random_uniform(5) + 1; //to get the range 1 - 5

Get randomFloat Fails

Why does my method return values < 0.4 in some cases?
e.g. 0.225501
#define ARC4RANDOM_MAX 0x100000000
float myVar = [self randomFloat:0.4 to:2];
- (float)randomFloat:(int)from to:(int)to
{
return ((double)arc4random() / ARC4RANDOM_MAX) * (to - from) + from;
}
You are casting your parameters to integers (which in your case changes your range to between 0 and 2), change the parameters to be float.
- (float)randomFloat:(float)from to:(float)to
when dividing and using floats the precision of the decimals is sometimes lost. Maybe you can use a long with N fixed number of digits and place the decimal point before those digits. The other day I was getting strange results when adding (1 + (3/10))= should be 1.3 but I always had something like 1.29995 . Hope it helps

pow function in Objective-c

I am implementing a math calculation in Objective-C in which i have used pow(<#double#>, <#double#>) function but it behaves weird.
I am trying to solve below math
100 *(0.0548/360*3+powf(1+0.0533, 3/12)/powf(1+0.0548, 3/12))
For same math, result of excel and xcode is different.
Excel output = 100.01001 (correct)
NSLog(#"-->%f",100 *(0.0548/360*3+powf(1+0.0533, 3/12)/powf(1+0.0548, 3/12)));
Xcode output = 100.045667 (wrong)
Now as everyone knows 3/12 = 0.25.
When i replace *3/12* with 0.25 in above math than xcode returns true result as below
Excel output = 100.01001 (correct)
NSLog(#"-->%f",100 *(0.0548/360*3+powf(1+0.0533, 0.25)/powf(1+0.0548, 0.25)));
Xcode output = 100.010095 (correct)
Anyone knows why pow function behave weird like this?
Note: I have also used powf but behavior is still same.
3/12, when you're doing integer math, is zero. In languages like, C, C++, ObjC and Java an expression like x / y containing only integers gives you an integral result, not a floating point one.
I suggest you try 3.0/12.0 instead.
The following C program (identical behaviour in this case to ObjC) shows this in action:
#include <stdio.h>
#include <math.h>
int main (void) {
// Integer math.
double d = 100 *(0.0548/360*3+powf(1+0.0533, 3/12)/powf(1+0.0548, 3/12));
printf ("%lf\n", d);
// Just using zero as the power.
d = 100 *(0.0548/360*3+powf(1+0.0533, 0)/powf(1+0.0548, 0));
printf ("%lf\n", d);
// Using a floating point power.
d = 100 *(0.0548/360*3+powf(1+0.0533, 3.0/12.0)/powf(1+0.0548, 3.0/12.0));
printf ("%lf\n", d);
return 0;
}
The output is (annotated):
100.045667 <= integer math gives wrong answer.
100.045667 <= the same as if you simply used 0 as the power.
100.010095 <= however, floating point power is okay.

Resources