NumPy: Convert the values of Centigrade degrees into Fahrenheit degrees and vice versa
NumPy: Array Object Exercise-14 with Solution
Write a NumPy program to convert Centigrade degrees into Fahrenheit degrees. Centigrade values are stored in a NumPy array.
Sample Array:
Values in Fahrenheit degrees [0, 12, 45.21, 34, 99.91]
Values in Centigrade degrees [-17.78, -11.11, 7.34, 1.11, 37.73, 0. ]
Sample Solution:
Fahrenheit to Celsius:
Python Code:
# Importing the NumPy library with an alias 'np'
import numpy as np
# List of Fahrenheit values
fvalues = [0, 12, 45.21, 34, 99.91, 32]
# Creating a NumPy array from the Fahrenheit values list
F = np.array(fvalues)
# Printing the Fahrenheit values
print("Values in Fahrenheit degrees:")
print(F)
# Converting Fahrenheit values to Centigrade degrees and printing the result
print("Values in Centigrade degrees:")
print(np.round((5 * F / 9 - 5 * 32 / 9), 2))
Sample Output:
Values in Fahrenheit degrees: [ 0. 12. 45.21 34. 99.91 32. ] Values in Centigrade degrees: [-17.78 -11.11 7.34 1.11 37.73 0. ]
Explanation:
In the above code -
fvalues = [0, 12, 45.21, 34, 99.91, 32]: A list of temperature values in Fahrenheit.
F = np.array(fvalues): Converts the list of fvalues into a NumPy array called F.
np.round((5*F/9 - 5*32/9), 2): Applies the formula to convert Fahrenheit to Celsius for each value in the NumPy array ‘F’. The np.round() function is used to round the resulting values to 2 decimal places.
Finally print() function prints the resulting NumPy array containing the converted temperature values in Celsius.
Celsius to Fahrenheit:
Python Code:
import numpy as np
cvalues = [-17.78, -11.11, 7.34, 1.11, 37.73, 0]
C = np.array(cvalues)
print("Values in Centigrade degrees:")
print(C)
print("Values in Fahrenheit degrees:")
print(np.round((9*C/5 + 32),2))
Sample Output:
Values in Centigrade degrees: [-17.78 -11.11 7.34 1.11 37.73 0. ] Values in Fahrenheit degrees: [-0. 12. 45.21 34. 99.91 32. ]
Python-Numpy Code Editor:
Previous: Write a NumPy program to create an empty and a full array.
Next: Write a NumPy program to find the real and imaginary parts of an array of complex numbers
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/numpy/python-numpy-exercise-14.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics