c++ - Working with R and .C to return dot product -


i trying return inner product of 2 vectors in .c r. after want function return true if inner product equal 0 , false otherwise. have written small .cpp function calculates inner product correct. when have vector of length 2 e.g <- c(5,-5) b <- c(5,5)

this returns 0 result , true result equal zero.

however when increase length of vector in r calling code e.g <- c(5,-5,4) b <- c(5,5,4)

it returns 16 result fine returns true incorrect result not equal zero.

can understand doing wrong here?

the code below .c

#include <r.h> extern "c" {     void test(int * x1, int * x2, int * len, int * result, bool * tf)     {         int n = *len;         *result = 0;         (int = 0; < n; i++)         {             *result = *result + x1[i] * x2[i];             if (*result == 0)             {                 *tf = true;             }         }     } } 

i have changed code

#include <r.h>  extern "c" {    void test (int * x1, int * x2, int * len, int * result, int * tf)  // void test (int * x1, int * x2, int * result)   {     int n = *len ;       *result = 0;       (int = 0; < n; i++)          *result += x1[i] * x2[i];        *tf = *result == 0;     }   } 

and when use r call below

a <- c(-5,5,4) b <- c(5,5,3) len <- length(a) c <- 0 ans <- false  .c("test", x1 = as.integer(a), x2 = as.integer(b),     len = as.integer(length(a)),    result = as.integer(c),    tf = as.logical(ans)) 

the output

$x1 [1] -5  5  4  $x2 [1] 5 5 3  $len [1] 3  $result [1] 12  $tf [1] true 

since result not 0 tf should false , when vector of length 1 or 2. when increase length 3 or more happen. can please?

your code buggy. here fixed version:

#include <r.h> extern "c" {    void isorthn (int * x1, int * x2, int * len, int * result, bool * tf)    {       int n = *len ;       *result = 0;       (int = 0; < n; i++)          *result += x1[i] * x2[i];        *tf = *result == 0;    }    } 

basically, out without ever initializing tf. moving test outside loop, simpler, cleaner , 1 sees *tf's value functionally dependent on result being 0.


Comments