Skip to content

Commit f92562e

Browse files
author
peng.li24
committed
refactor(numpycpp): update elementwise_py.h
1 parent 48e1bf8 commit f92562e

1 file changed

Lines changed: 12 additions & 2 deletions

File tree

numpycpp/elementwise_py.h

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,8 @@ inline py::array astype(const py::array& arr, const std::string& dtype) {
276276
}
277277

278278
// float64
279+
_ASTYPE_CASE(double, "float64", double) // 自转换
280+
_ASTYPE_CASE(double, "double", double)
279281
_ASTYPE_CASE(double, "float32", float)
280282
_ASTYPE_CASE(double, "float", float)
281283
_ASTYPE_CASE(double, "int", int)
@@ -285,18 +287,23 @@ inline py::array astype(const py::array& arr, const std::string& dtype) {
285287
// float32
286288
_ASTYPE_CASE(float, "float64", double)
287289
_ASTYPE_CASE(float, "double", double)
290+
_ASTYPE_CASE(float, "float", double) // numpy 约定: np.float32(1).astype(float) → float64
291+
_ASTYPE_CASE(float, "float32", float) // 自转换: 无操作
288292
_ASTYPE_CASE(float, "int", int)
289293
_ASTYPE_CASE(float, "int32", int)
290294
_ASTYPE_CASE(float, "int64", int64_t)
291295
_ASTYPE_CASE(float, "bool", bool)
292296
// int32
297+
_ASTYPE_CASE(int, "int32", int) // 自转换
298+
_ASTYPE_CASE(int, "int", int)
293299
_ASTYPE_CASE(int, "float64", double)
294300
_ASTYPE_CASE(int, "double", double)
295301
_ASTYPE_CASE(int, "float32", float)
296302
_ASTYPE_CASE(int, "float", float)
297303
_ASTYPE_CASE(int, "int64", int64_t)
298304
_ASTYPE_CASE(int, "bool", bool)
299305
// int64
306+
_ASTYPE_CASE(int64_t, "int64", int64_t) // 自转换
300307
_ASTYPE_CASE(int64_t, "float64", double)
301308
_ASTYPE_CASE(int64_t, "double", double)
302309
_ASTYPE_CASE(int64_t, "float32", float)
@@ -305,6 +312,7 @@ inline py::array astype(const py::array& arr, const std::string& dtype) {
305312
_ASTYPE_CASE(int64_t, "int32", int)
306313
_ASTYPE_CASE(int64_t, "bool", bool)
307314
// bool
315+
_ASTYPE_CASE(bool, "bool", bool) // 自转换
308316
_ASTYPE_CASE(bool, "float64", double)
309317
_ASTYPE_CASE(bool, "double", double)
310318
_ASTYPE_CASE(bool, "float32", float)
@@ -314,8 +322,10 @@ inline py::array astype(const py::array& arr, const std::string& dtype) {
314322
_ASTYPE_CASE(bool, "int64", int64_t)
315323
#undef _ASTYPE_CASE
316324

317-
throw std::runtime_error("astype: unsupported conversion " +
318-
std::string(py::str(dt)) + " -> " + dtype);
325+
throw std::runtime_error(
326+
"astype: unsupported conversion " + std::string(py::str(dt)) +
327+
" -> " + dtype + ". Available targets: float64/double, float32/float, "
328+
"int/int32, int64, bool. Also accepts self-conversion (e.g. float32->float32).");
319329
}
320330

321331
/// float64 → float32 → float64 roundtrip

0 commit comments

Comments
 (0)