RcppArmadillo和C ++部门问题 [英] RcppArmadillo and C++ division issue
问题描述
关于RcppArmadillo的一个非常简单的问题.尝试将向量乘以标量,并根据语法的微小变化获得不同的结果.
A very simple question regarding RcppArmadillo. Trying to multiply a vector by a scalar, and getting different results depending on small changes in syntax.
有什么想法吗?
// [[Rcpp::depends("RcppArmadillo")]]
// [[Rcpp::export]]
arma::vec funtemp(arma::vec x)
{
// return(x/10); // this works
// return((1/10)*x); // this does not work
return(x*(1/10)); // this does not work
}
推荐答案
啊,C ++中很好的integer
vs. double
除法问题.在开始之前,请注意:默认情况下,arma::vec
是double
,而1
,10
,1/10
都是int
s ...
Ahh, the good ol' integer
vs. double
division problem in C++. Before we begin, note that: arma::vec
is by default a double
and 1
, 10
, 1/10
are all int
s...
让我们分别看一下您的功能:
Let's take a look at your functions separately:
#include <RcppArmadillo.h>
// [[Rcpp::depends("RcppArmadillo")]]
// [[Rcpp::export]]
arma::vec funtemp_one(arma::vec x)
{
return(x/10); // this works
}
// [[Rcpp::export]]
arma::vec funtemp_two(arma::vec x)
{
return((1/10)*x); // this does not work
}
// [[Rcpp::export]]
arma::vec funtemp_three(arma::vec x)
{
return(x*(1/10)); // this does not work
}
因此,当我们解决您的问题时,我们得到:
Therefore, when we run through your problem we get:
> funtemp_one(1)
[,1]
[1,] 0.1
> funtemp_two(1)
[,1]
[1,] 0
> funtemp_three(1)
[,1]
[1,] 0
在以后的功能(例如1/10
)中,正在使用的operator/
是基于int
的除法.结果,输入2 int
并返回1 int
.如果结果不能被整除,则最终将返回零,因为它在整数范围之外.
In the later functions (e.g. the 1/10
), the operator/
that is being used is int
based division. As a result, 2 int
s enter and 1 int
is returned. If the result is not divisible, then you end up with a zero being returned as it is outside of the integer scope.
为了使用返回双精度型的双精度型,必须将至少一个int
显式转换为double
.默认情况下,在第一种情况下会发生这种情况,因为由于arma::vec
的结构,您拥有double
/int
.第二和第三种情况具有int/int
结构,可以通过两种方式处理:1.在int
之后使用.0
或2.使用double(int)
In order to use the double version, which returns a double, at least one of the int
s must be explicitly cast to a double
. This happens by default in the first case as you have a double
/int
due to arma::vec
's structure. The second and third cases have an int/int
structure that can be dealt with in two ways: 1. use a .0
after the int
or 2. explicitly cast the value as a double with double(int)
例如
// [[Rcpp::export]]
arma::vec funtemp_four(arma::vec x)
{
return(x*(1/10.0)); // this works
}
// [[Rcpp::export]]
arma::vec funtemp_five(arma::vec x)
{
return(x*(1/double(10))); // this works
}
将给出您的期望:
> funtemp_four(1)
[,1]
[1,] 0.1
> funtemp_five(1)
[,1]
[1,] 0.1
这篇关于RcppArmadillo和C ++部门问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!