Search code examples
pythonsqrtmath.sqrt

math.sqrt() ValueError: math domain error


Im trying to plot out a graph with matplotlib and calculus, but the math.sqrt() of my f(x) function doesnt work. I need to sqhare root 2*x-1. As seen in the code

import matplotlib.pyplot as plt
import math

def f(x):
    return math.sqrt(2*x-1)

plt.plot([0, 1, 2, 3, 4], [f(0), f(1), f(2), f(3), f(4)])
plt.show()

And it gives an error saying ValueError: math domain error. Which i am not sure how to do it the right way/fix it


Solution

  • This doesn't work because you are trying to find the root of a negative number, removing the "0"s from the array lets the code run without error.