RcppArmadillo和C ++部门问题 [英] RcppArmadillo and C++ division issue

查看:98
本文介绍了RcppArmadillo和C ++部门问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于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::vecdouble,而1101/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 ints...

让我们分别看一下您的功能:

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 ints 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 ints 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆