Ok, so while practicing python, plotting and quadratic equations - I found this weird behaviour in plotting.
The function 'func' defines one of the solution to a quadratic equation. The solution being 0.5(x+1 - sqrt((x+1)^2 - 4x))
And so I tried plotting this value against different x values. I get something similar to this -> Click Here

A friend pointed out that the solution actually reduces to 1.0 - therefore the plot should be a horizontal line passing through y at 1.0

Obviously that is not what I'm getting.

Can someone please explain why I'm getting a weird plot? Thanks in advance! :)

import matplotlib.pyplot as plt
from math import *


def func(x):
    B = x + 1.0
    C = x
    y = 0.5 * (B - sqrt(B ** 2 - 4 * C))
    return y


def frange(start, stop, step):
    i = start
    while i < stop:
        yield i
        i += step

x = []
y = []

for i in frange(0.0, 2.0, 0.01):
    x.append(i)
    y.append(func(i))
plt.scatter(x, y)
plt.show()

Your function evaluates to 1 for x >= 1 and to < 1 for x < 1. So the behaviour is completely normal. Try out and make a table of values between -10 < x < 10.

commented: indeed +14

Yes , you mistakenly believe that the function equals 1. The square root is in fact sqrt((x-1)**2) Mathematically, it has the same value as abs(x-1), which is x-1 when x >= 1 and 1-x when x <= 1. It means that your function's value is x when x < 1.

Thank you for your answers, I get it now. silly me :P

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.