Reputation: 35
I am trying to add the float values of a ruby array in C with RubyInline (ruby 1.9.2). The expected output should be a float value. Here is my code:
require 'inline'
class ArrayMath
inline :C do |builder|
builder.c "
VALUE sum(VALUE arr){
int size = RARRAY_LEN(arr);
VALUE *c_arr = RARRAY_PTR(arr);
int i, x;
float sum = 0.0;
for (i=0; i<size; i++)
{
x = NUM2DBL(c_arr[i]);
sum += x;
}
return( rb_float_new(sum) );
}"
end
end
running this in the console
ArrayMath.new.sum([1,2.7])
outputs 3.0 Obviously the expected result is 3.7
Upvotes: 0
Views: 438
Reputation: 206861
x
is an int
in your C code. Change that to a float
(or double
) if you don't want the result of NUM2DBL
truncated.
Or do away with that temporary altogether and write:
sum += NUM2DBL(c_arr[i]);
Upvotes: 2