nc::sum(NdArray<bool>) gives wrong result
holyYodu opened this issue · comments
holyYodu commented
Describe the bug
Thanks for your excellent work! when using NumCPP, I found that the nc::sum(NdArray) will give the wrong result
To Reproduce
Steps to reproduce the behavior:
#include "NumCpp.hpp"
#include <cstdlib>
#include <iostream>
#include <numeric>
int main()
{
nc::NdArray<bool> c = {false, false, true, true};
std::cout << c;
std::cout << nc::sum(c);
return EXIT_SUCCESS;
}
the given output is: 1, which should be 2.
(base) NumCpp_demo/build [ ./HelloWorld ] 5:34 PM
[[0, 0, 1, 1, ]]
[[1, ]]
(base) NumCpp_demo/build [ ] 5:35 PM
Expected behavior
I experiment with numpy and numpy gives the right output
In [1]: import numpy as np
In [2]: a = np.array([False, False, True, True])
In [3]: a
Out[3]: array([False, False, True, True])
In [4]: np.sum(a)
Out[4]: 2
David Pilger commented
NumCpp
returns the same dtype
as the input NdArray
, leaving the onus on the user to make sure the array is of a correct dtype
to not overflow the summation.
#include "NumCpp.hpp"
#include <cstdint>
#include <iostream>
int main()
{
nc::NdArray<bool> c = {false, false, true, true};
std::cout << c << '\n';
// return is NdArray<bool> therefore cannot hold a value > 1
std::cout << nc::sum(c);
// cast to int for summation so that return is NdArray<int>
std::cout << nc::sum(c.astype<int>());
// or better yet, leave as a bool and don't sum at all
std::cout << nc::count_nonzero(c);
return 0;
}
[[0, 0, 1, 1, ]]
[[1, ]]
[[2, ]]
[[2, ]]