[Rcpp-devel] int double multiplication

Matt D. matdzb at gmail.com
Tue Jun 21 22:19:49 CEST 2016


Hi,

On 6/21/2016 16:33, Andreas Prescher wrote:
> void f(double d) {
> 	int i = vector.size() * d;
> }
A quick note to add to the other answers: You don't want to be using 
`int` here.
Especially since you mention a 64-bit platform -- but IMHO it's a bad 
idea in general.
If you'd like a simple rule of thumb, here goes: Avoid using `int` for 
anything by default -- especially anything involving 
sizes/indexes/counting. Yes, there are exceptional lucky cases when you 
may be able to get away with an `int`, but taking these into account is 
brittle and anything but "simple."

Your `vector.size()`, assuming you're dealing with `vector` of type 
`std::vector<int>` (as in your later example), has type 
`std::vector<int>::size_type` -- which (on your 64-bit platform) will be 
64-bits.
See: http://en.cppreference.com/w/cpp/container/vector/size
In contrast, type `int` is at most 32-bits: 
http://en.cppreference.com/w/cpp/language/types

If the value of the expression involving the vector size value is larger 
than what you can store in an `int`, then the size_type->double->int 
conversion you're doing when storing to `i` will cause undefined 
behavior due to overflow:
http://blog.frama-c.com/index.php?post/2013/10/09/Overflow-float-integer

While you may (or may not) be in a particularly lucky special case when 
the size value just happens to fit in the 32-bits on one occasion, you 
may not be on another.
Instead of spending time on deciding "is `int` luckily going to work 
today" (or performing an interval analysis involving making guesses 
about potential input sample sizes / the ranges of `vector.size()` and 
`d`) it's simpler to just use the proper type at all times.

Now, regarding the rounding and the "adding 0.5" trick, there are some 
subtleties here worth being aware of:
http://blog.frama-c.com/index.php?post/2013/05/02/nearbyintf1

If you can use C++11 the right choice would be to use these:
http://en.cppreference.com/w/cpp/numeric/math/round

Refs:
https://randomascii.wordpress.com/2012/04/05/floating-point-complexities/
https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/

Best,

Matt



More information about the Rcpp-devel mailing list