TUTORIALAI 与数据科学FETCHED
PyTorch torch.can_cast 函数
PyTorch torch.can_cast 函数 Pytorch torch 参考手册 torch.can_cast 是 PyTorch 中用于检查类型转换是否可执行的函数。检查是否可以从源数据类型转换为目标数据类型。 函数定义 torch.can_cast(from_dtype, to_dtype) 使用示例 实例 [mycode4 type='python'] import torch # 检查类..
更新于 2026/7/16
教程详情页默认 noindex。
PyTorch torch.can_cast 函数
torch.can_cast 是 PyTorch 中用于检查类型转换是否可执行的函数。检查是否可以从源数据类型转换为目标数据类型。
函数定义
torch.can_cast(from_dtype, to_dtype)
使用示例
实例
import torch
# 检查类型转换是否可执行
print(torch.can_cast(torch.float32, torch.int32)) # True
print(torch.can_cast(torch.float64, torch.int8)) # True
print(torch.can_cast(torch.int64, torch.bool)) # True
# 从 bool 转换
print(torch.can_cast(torch.bool, torch.float32)) # True
# 检查类型转换是否可执行
print(torch.can_cast(torch.float32, torch.int32)) # True
print(torch.can_cast(torch.float64, torch.int8)) # True
print(torch.can_cast(torch.int64, torch.bool)) # True
# 从 bool 转换
print(torch.can_cast(torch.bool, torch.float32)) # True
Pytorch torch 参考手册