SciPy - convert_temperature() 方法

SciPy convert_temperature() 方法用于以摄氏、开氏、华氏和兰氏等任意一种标度的形式计算温度标度。

以下是理解各种标度的关键 −

  • 摄氏 − 温度单位。
  • 华氏 − 这是水在 32 度结冰并在 212 度沸腾时的温度标度。
  • 开氏 − 这是 0 反映时的温度单位。
  • 兰氏 −温度的绝对单位。

语法

以下是 SciPy convert_temperature() 方法的语法 −

convert_temperature(val, old_scale, new_scale)

参数

此方法接受以下参数 −

  • val− 指定温度范围值。
  • old_scale− 指定原始字符串。
  • new_scale−指定温度将转换为的新字符串。

返回值

此函数返回浮点值数组。

示例 1

以下是基本的 SciPy convert_temperature() 方法,说明了摄氏、华氏和开尔文的转换。

import scipy.constants as const

def convert_temperature(value, from_unit, to_unit):
   if from_unit == to_unit:
       return value

    # 首先将输入温度转换为摄氏度
   if from_unit == 'Celsius':
       temp_c = value
   elif from_unit == 'Fahrenheit':
       temp_c = (value - 32) * 5/9
   elif from_unit == 'Kelvin':
       temp_c = value - const.zero_Celsius
   else:
       raise ValueError("Unsupported temperature unit")

    # 从摄氏度转换为所需单位
   if to_unit == 'Celsius':
       return temp_c
   elif to_unit == 'Fahrenheit':
       return temp_c * 9/5 + 32
   elif to_unit == 'Kelvin':
       return temp_c + const.zero_Celsius
   else:
       raise ValueError("Unsupported temperature unit")

# 显示结果
print(convert_temperature(100, 'Celsius', 'Fahrenheit')) 
print(convert_temperature(32, 'Fahrenheit', 'Celsius'))  
print(convert_temperature(273, 'Kelvin', 'Celsius'))   

输出

上述代码产生以下结果 −

212.0
0.0
-0.14999999999997726

示例 2

下面的示例使用更多的 scipy 常量将基本单位转换为温度单位。

import scipy.constants as const

def convert_temperature(value, from_unit, to_unit):
   if from_unit == to_unit:
       return value

   # 将输入转换为开尔文
   if from_unit == 'Celsius':
       temp_k = value + const.zero_Celsius
   elif from_unit == 'Fahrenheit':
       temp_k = (value - 32) * 5/9 + const.zero_Celsius
   elif from_unit == 'Kelvin':
       temp_k = value
   else:
       raise ValueError("Unsupported temperature unit")

   # 将开尔文转换为所需单位
   if to_unit == 'Celsius':
       return temp_k - const.zero_Celsius
   elif to_unit == 'Fahrenheit':
       return (temp_k - const.zero_Celsius) * 9/5 + 32
   elif to_unit == 'Kelvin':
       return temp_k
   else:
       raise ValueError("Unsupported temperature unit")

# 显示结果
print(convert_temperature(100, 'Celsius', 'Fahrenheit')) 
print(convert_temperature(32, 'Fahrenheit', 'Kelvin'))    
print(convert_temperature(273.15, 'Kelvin', 'Celsius'))   

输出

上述代码产生以下结果 −

212.0
273.15
0.0

scipy_reference.html