1

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

tristansokol
  • 4,054
  • 2
  • 17
  • 32
TrackLab
  • 32
  • 1
  • 7
  • 6
    `2*x - 1` is negative for `x == 0`. `math.sqrt` expects values for which the answer would be a real number, i.e. any `x` with `x >= 0`. – timgeb Oct 16 '18 at 20:31
  • @timgeb Oh I see, thank you. I removed the 0 from the list. – TrackLab Oct 16 '18 at 20:34
  • 1
    If you do want to take the roots of negative values, you should use `cmath.sqrt` instead, which will produce complex results – Patrick Haugh Oct 16 '18 at 20:35

1 Answers1

1

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.