относительная погрешность, % in python

To calculate the relative error % in Python, you can use the following code:

main.py
import math

def relative_error(actual_value, predicted_value):
    # Calculate the absolute error
    abs_error = abs(predicted_value - actual_value)
    
    # Calculate the relative error
    rel_error = abs_error / actual_value
    
    # Return the relative error as a percentage
    return round(rel_error * 100, 2)
322 chars
12 lines

Here, we are defining a function relative_error which takes two arguments actual_value and predicted_value. The function then first calculates the absolute error by taking the absolute difference between the predicted and actual values. It then calculates the relative error by dividing the absolute error by the actual value. Finally, it returns the relative error as a percentage by multiplying it by 100 and rounding it to two decimal points.

You can call this function by passing in your actual and predicted values:

main.py
print(relative_error(10, 8))  # Output: 20.0
print(relative_error(15.5, 13.2))  # Output: 14.84
96 chars
3 lines

In the above example, we are calling the relative_error function with actual value of 10 and predicted value of 8. The output would be 20.0 indicating a relative error of 20%.

gistlibby LogSnag