Skip to content Skip to sidebar Skip to footer

Python: Quadriatic Graph Multiple Numbers Error

I have created a code to print the equation y=x^2+3 However it looks like every time I finish it the y axis has multiple numbers, like top to bottom-19,19,19,19,19,17,17,9,7,7,7 et

Solution 1:

As you stated, you need to draw the graph "backwards": first print the empty lines between the current y and the previous one, then print the current y value. You need to put the "*" print at the end of the outer loop (the loop on x)

Next issue is the number of empty lines. Between 19 and 12, you should only have 6 empty lines, because you don't count the line 19 and the line 12.

old=19new=12
#your code
old-new+1=8
#actual number ofempty lines
old-new-1=6

Next, you have repeated numbers in the y axis because you're always printing the same y. Here:

for lines inrange(0,difference+1):
    print('{0:>3}'.format(str(y)+'|'))

The y stays the same, and is equal to the "new" value. You need to decrease y from "old value -1" to "new value +1". Something like oldY=oldY-1, print(oldY).

Finally, you never update oldY. At the end of the outer loop, you should have oldY=y

Solution 2:

You could also calculate your values of y in advance and iterate over all y values, inserting markers when a y value matches one of your values to plot, as follows:

print('{0:>{width}}'.format('y', width=2))

f = lambda x: x**2 + 3

xmax = 4
xs = range(xmax+1)
ys = [f(x) for x in xs]
ymax = max(ys)
xscale = 5
i = len(ys)-1for y inrange(ymax,-1,-1):
    # The y-axisprint('{0:>3}|'.format(y), end='')
    if i >= 0and y==ys[i]:
        print('{marker:>{width}}'.format(marker='*', width=xs[i]*xscale))
        i -= 1else:
        print()
print('   L' + '_'*len(xs)*xscale)
print('    ' + ''.join(['{x:>{xscale}}'.format(x=x, xscale=xscale) for x in xs[1:]]))

Output:

y
 19|                   *
 18|
 17|
 16|
 15|
 14|
 13|
 12|              *
 11|
 10|
  9|
  8|
  7|         *
  6|
  5|
  4|    *
  3|*
  2|
  1|
  0|
   L_________________________
        1    2    3    4

Post a Comment for "Python: Quadriatic Graph Multiple Numbers Error"