Search code examples
pythonnumpymatplotlibfloorceil

How can I plot a discontinuous ceiling function?


Here is the code I am using to plot graph of ceiling function in python.

import math
import numpy as np
import matplotlib.pyplot as plt 
x = np.arange(-5, 5, 0.01)
y = np.ceil(x)
plt.plot(x,y)
plt.xlabel('ceil(x)')
plt.ylabel('graph of ceil (x)')
plt.title('graph of ceil (x)')
plt.show()

I tried, np.arange to consider float values between two integers, but though can't plot that correct graph which is disconnected and shows jump in graph as we draw in maths.


Solution

  • I guess this is what you want:

    x = np.arange(-5, 5, 0.01)
    y = np.ceil(x)
    
    plt.xlabel('ceil(x)')
    plt.ylabel('graph of ceil (x)')
    plt.title('graph of ceil (x)')
    
    for i in range(int(np.min(y)), int(np.max(y))+1):
        plt.plot(x[(y>i-1) & (y<=i)], y[(y>i-1) & (y<=i)], 'b-')
    
    plt.show()
    

    enter image description here