Skip to content

Commit fbbca91

Browse files
committed
fixed linspace corner case
1 parent b5f4acc commit fbbca91

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

include/xtensor/xbuilder.hpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -402,7 +402,7 @@ namespace xt
402402
inline auto linspace(T start, T stop, std::size_t num_samples = 50, bool endpoint = true) noexcept
403403
{
404404
using fp_type = std::common_type_t<T, double>;
405-
fp_type step = fp_type(stop - start) / fp_type(num_samples - (endpoint ? 1 : 0));
405+
fp_type step = fp_type(stop - start) / std::fmax(fp_type(1), fp_type(num_samples - (endpoint ? 1 : 0)));
406406
return cast<T>(detail::make_xgenerator(detail::arange_generator<fp_type>(fp_type(start), fp_type(stop), step), {num_samples}));
407407
}
408408

test/test_xbuilder.cpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,25 @@ namespace xt
187187
ASSERT_EQ(m_assigned(3), at_3);
188188
}
189189

190+
TEST(xbuilder, linspace_1_point)
191+
{
192+
xt::xarray<double> a = linspace<double>(0., 0., 1, false);
193+
decltype(a)::shape_type expected_shape = {1};
194+
EXPECT_EQ(a.dimension(), size_t(1));
195+
EXPECT_EQ(a.shape(), expected_shape);
196+
EXPECT_EQ(0., a(0));
197+
198+
xt::xarray<double> b = linspace<double>(0., 0., 1, true);
199+
EXPECT_EQ(b.dimension(), size_t(1));
200+
EXPECT_EQ(b.shape(), expected_shape);
201+
EXPECT_EQ(0., b(0));
202+
203+
xt::xarray<double> c = linspace<double>(0., 2., 1, true);
204+
EXPECT_EQ(c.dimension(), size_t(1));
205+
EXPECT_EQ(c.shape(), expected_shape);
206+
EXPECT_EQ(0., b(0));
207+
}
208+
190209
TEST(xbuilder, linspace_n_samples_endpoint)
191210
{
192211
auto ls = linspace<float>(20.f, 50.f, 100, false);

0 commit comments

Comments
 (0)