Using Ceil and Integers

So, I just got my class from a school project that I excelled at, but the grader took five points away because I didn't call to sink (...). Its a parallel computational course using CUDA, but the question is not directly related to any CUDA feature.

Here is the "offensive" line:

dim3 dimGrid(n / dimBlock.x, n / dimBlock.y);

      

His statement is that I should have done:

dim3 dimGrid(ceil(n / dimBlock.x), ceil(n / dimBlock.y));

      

So my question is, why would I mark this if n and dimBlock. * are integers? Their result will be calculated before ceil is even named and truncated. So it seems silly to celebrate.

The examples below show that GCC will optimize the call anyway when using -O2.

With ceiling:

#include <stdio.h>
#include <math.h>

int main()
{
        int m = 3, n = 5, o;

        o = ceil(n / m);
        printf("%d\n", o);
        return 0;
}

      

Without:

#include <stdio.h>
#include <math.h>

int main()
{
        int m = 3, n = 5, o;

        o = n / m;
        printf("%d\n", o);
        return 0;
}

      

While I only understand his five points, I still want to understand why, if I am completely wrong.

+3


source to share


2 answers


The grader probably meant that you need to use the faction ceiling n/d

, which is perfectly correct: this way there will be enough blocks to cover n

, with the last block being incomplete.

This does not mean that a conforming implementation is performed with a C expression ceil(n/d)

. Indeed, C /

is an integer division and discards the decimal part, effectively taking up half a fraction.



You can use instead ceil((double)n/(double)d)

.

But my favorite way to be without conversion pair: (n+d-1)/d

.

+2


source


here, m = 3, n = 5 so that n / m = 1.67 (approximately); since you assign it to o, which is of type int, it truncates it. those. stores only the integer part, not the decimal part, so we have o = 1. Although if you use ceil (n / m), the output will be 2, which will then be assigned to o. that is, o = 2.



-1


source







All Articles