Use class method as `op` argument to `accumulate` - c++11

I'm trying to create a class that calculates its variance from a vector<float>. It should do this by using its previously calculated this->mean in diffSquaredSum. I'm trying to call the method diffSquaredSum inside of accumulate but have no idea what the magical syntax is.
What is the correct syntax to use the diffSquaredSum class method as the op argument to accumulate in setVariance?
float diffSquaredSum(float sum, float f) {
// requires call to setMean
float diff = f - this->mean;
float diff_square = pow(diff,2);
return sum + diff_square;
}
void setVariance(vector<float>& values) {
size_t n = values.size();
double sum = accumulate(
values.begin(), values.end(), 0,
bind(this::diffSquaredSum));
this->variance = sum / n;
}

double sum = std::accumulate(
values.begin(),
values.end(),
0.f,
[&](float sum, float x){ return diffSquaredSum(sum,x);}
);
bind is only rarely useful. Prefer lambdas, they are easier to write and read.
You could instead get fancy with binding, but why?

Related

How to Determine How many cycles it would take to get a given value to 0 by decreasing it by a given amount

This is my problem, i need to take double onHand and reduce it by the double consume, then determine how many cycles it would take to reach 0. then use Math.Round 3 to round it to 3 decimal points.
public static int Test4(double onHand, double consume)
{
int answer = 1;
for (int i = (int)(consume); i > onHand; i--)
{
answer -= (int)onHand;
}
return answer;
}
I tried creating multiple variables like introducing decimals, casting the doubles into floats and ints but i can only get to the point where my answer outputs the int of the onHand.
You just have to make a division.
Assuming onHand is 3.02 and consume is 0.24, you divide them like onHand / consume and that will result in 12.583333. You will have to ceil or round-up the value (13). That is the number of times it'll go trough the loop to reach or pass 0.
Example
public static int Test4(double onHand, double consume)
{
double answer = (decimal)onHand / (decimal)consume;
return (int) Math.Ceiling(answer);
}
I'm no expert on C# so I don't know if the casting is neccesary.
public static int Test4(double onHand, double consume)
{
int answer = 1;
for (int i = 0; i < consume; i++)
{
answer = (int)((decimal)onHand / (decimal)consume);
}
return answer;
}

Is it possible to convert this method in to java 8 using streams? If yes how?

Suppose i have one method which takes two arrays of double type than takes a local variable 'sum' of double type with init value of zero. After that a for loop iterates from start to end and subtract like this a1[i] - b[i] and save result into another local variable called minus. Than do minus * minus and sum it with the existing value in sum variable and at the end sum.
I am confuse how can i implement this in java 8 using streams. Can anybody help me?
public double calculate(double[] a1, double[] b2, int start, int end) {
double sum = 0.0;
for(int i = start; i < end; i++) {
final double minus = a1[i] - b2[i];
sum += minus * minus;
}
return sum;
}
return IntStream.range(start, end)
.mapToDouble(x -> a1[x] - b2[x])
.map(x -> x * x)
.sum();

Cannot convert from float to int Processing/Java

I have some code here:
int mutate(float x){
if (random(1) < .1){
float offset = randomGaussian()/2;
float newx = x + offset;
return newx;
} else {
return x;
}
}
This code gives an error on both samples of returning a value saying "Type mismatch: Cannot convert from float to int." What is wrong with my code?
Thanks in advance.
You need to change the return type to float in order to return decimal values (if that's what you are interested in):
float mutate(float x){
if (random(1) < .1){
float offset = randomGaussian()/2;
float newx = x + offset;
return newx;
} else {
return x;
}
}
First off, remember what int and float are:
int can only hold whole numbers without decimal places, like 1, 42, and -54321.
float can hold numbers with decimal places, like 0.25, 1.9999, and -543.21.
So, you need to figure out what you meant to return from your function: should it be an int or a float value? If it's supposed to be a float value, then you can simply change the return type of the function to float. If you want it to return an int value, then you'll have to rethink the logic inside your function so it's using int values instead.
Note that you can convert from a float to an int using the int() function. More info can be found in the reference.

Processing - cannot convert float to int

I have a code like this:
float[] x = {5,11,17,23,26,23,18,12,7,4,5,6,7,6,3,2,5,5,4,3,3,5,10,18,26,32,26,18,10,5,2,10,12,14,15,9,8,14,13,9,7,5,3,8,17,33,49,32,16,7,3,1,13,16,23,31,26,25,30,22,14,9,7,0,1,9,38,101,38,9,0,1,0,12,17,32,60,89,88,59,30,15,8,6,6,14,19,10,279,10,19,14,8,3,6,10,26,89,360,359,88,25,9,4,2,10,30,82,259,1000,260,82,32,13,5,5,9,26,89,358,359,89,26,9,4,3,6,13,19,9,280,9,20,14,8,3,11,17,31,60,89,89,60,31,16,9,6,0,1,9,38,102,38,9,0,1,0,12,16,23,30,25,25,31,22,14,10,7,3,8,17,33,50,33,17,8,3,1,9,11,13,14,8,9,15,13,10,7,6,5,10,18,27,33,27,18,11,6,3,5,6,6,6,2,3,6,6,5,4,1,5,11,18,24,27,24,18,12,7,3};
void setup(){
size(620,620);
float k=1;
float q=0;
for (float j=0;j<height;j=j+30){
if(k%2!=0){
for(float i=30;i<width;i=i+60){
fill(kolor(x[q]));
rect(i,j,20,20);
q=q+1;
}
k++;
} else {
for(float i=0;i<width;i=i+60){
fill(kolor(x[q]));
rect(i,j,20,20);
q=q+1;
}
k++;
}
}
}
float kolor(float input){
return map(input,0,1000,0,255);
}
When I try to compile, I get "cannot convert float to int" error, connected with lines fill(kolor(x[q]));.
I tried changing this to fill((int)kolor(x[q]));.
Do you have any idea how to fix this?
The problem with line fill((int)kolor(x[q]) is that x is an array, and you can only access array members by using ints, while you access it using q which is a float.
Try changing float q = 0; to int q = 0;
By the way, it looks like java code, is it java?
Why are you using floats in the first place? You probably should be using ints, especially with the % in there.
Here is the signature of the fill() command, for those interested.

TERCOM algorithm - Changing from single thread to multiple threads in CUDA

I'm currently working on porting a TERCOM algorithm from using only 1 thread to use multiple threads. Briefly explained , the TERCOM algorithm receives 5 measurements and the heading, and compare this measurements to a prestored map. The algorithm will choose the best match, i.e. lowest Mean Absolute Difference (MAD), and return the position.
The code is working perfectly with one thread and for-loops, but when I try to use multiple threads and blocks it returns the wrong answer. It seems like the multithread version doesn't "run through" the calculation in the same way as the singlethread versjon. Does anyone know what I am doing wrong?
Here's the code using for-loops
__global__ void kernel (int m, int n, int h, int N, float *f, float heading, float *measurements)
{
//Without threads
float pos[2]={0};
float theta=heading*(PI/180);
float MAD=0;
// Calculate how much to move in x and y direction
float offset_x = h*cos(theta);
float offset_y = -h*sin(theta);
float min=100000; //Some High value
//Calculate Mean Absolute Difference
for(float row=0;row<m;row++)
{
for(float col=0;col<n;col++)
{
for(float g=0; g<N; g++)
{
f[(int)g] = tex2D (tex, col+(g-2)*offset_x+0.5f, row+(g-2)*offset_y+0.5f);
MAD += abs(measurements[(int)g]-f[(int)g]);
}
if(MAD<min)
{
min=MAD;
pos[0]=col;
pos[1]=row;
}
MAD=0; //Reset MAD
}
}
f[0]=min;
f[1]=pos[0];
f[2]=pos[1];
}
This is my attempt to use multiple threads
__global__ void kernel (int m, int n, int h, int N, float *f, float heading, float *measurements)
{
// With threads
int idx = blockIdx.x * blockDim.x + threadIdx.x;
int idy = blockIdx.y * blockDim.y + threadIdx.y;
float pos[2]={0};
float theta=heading*(PI/180);
float MAD=0;
// Calculate how much to move in x and y direction
float offset_x = h*cos(theta);
float offset_y = -h*sin(theta);
float min=100000; //Some High value
if(idx < n && idy < m)
{
for(float g=0; g<N; g++)
{
f[(int)g] = tex2D (tex, idx+(g-2)*offset_x+0.5f, idy+(g-2)*offset_y+0.5f);
MAD += abs(measurements[(int)g]-f[(int)g]);
}
if(MAD<min)
{
min=MAD;
pos[0]=idx;
pos[1]=idy;
}
MAD=0; //Reset MAD
}
f[0]=min;
f[1]=pos[0];
f[2]=pos[1];
}
To launch the kernel
dim3 dimBlock( 16,16 );
dim3 dimGrid;
dimGrid.x = (n + dimBlock.x - 1)/dimBlock.x;
dimGrid.y = (m + dimBlock.y - 1)/dimBlock.y;
kernel <<< dimGrid,dimBlock >>> (m, n, h, N, dev_results, heading, dev_measurements);
The basic problem here is that you have a memory race in the code, centered around the use of f as both some sort of thread local scratch space and an output variable. Every concurrent thread will be trying to write values into the same locations in f simultaneously, which will produce undefined behaviour.
As best as I can tell, the use of f as scratch space isn't even necessary at all and the main computational section of the kernel could be written as something like:
if(idx < n && idy < m)
{
for(float g=0; g<N; g++)
{
float fval = tex2D (tex, idx+(g-2)*offset_x+0.5f, idy+(g-2)*offset_y+0.5f);
MAD += abs(measurements[(int)g]-fval);
}
min=MAD;
pos[0]=idx;
pos[1]=idy;
}
[disclaimer: written in browser, use at own risk]
At the end of that calculation, each thread has its own values of min and pos. At a minimum these must be stored in unique global memory (ie. the output must have enough space for each thread result). You will then need to perform some sort of reduction operation to obtain the global minimum from the set of thread local values. That could be in the host, or in the device code, or some combination of the two. There is a lot of code already available for CUDA parallel reductions which you should be able to find by searching and/or looking in the examples supplied with the CUDA toolkit. It should be trivial to adapt them to your specify case where you need to retain the position along with the minimum value.

Resources