Colin Warn
Colin Warn

Reputation: 411

Graphing This Function as a Cumulative Distribution

I'm trying to create a cumulative distribution graph of the following function in Python, from -infinity to infinity:

enter image description here

Initially I tried this code I found online, which seems to work for functions such as x**2:

import numpy as np
import matplotlib.pyplot as plt
def graph(formula, x_range):
    x = np.array(x_range)
    y = eval(formula)
    plt.plot(x, y)
    plt.show()

#graph('(4/5)*(((x**4)/4)+x)', range(-100, 100))

graph('x**2', range(-100, 100))

Result: enter image description here

The problem is I'm not sure how to translate this code to take into account the other conditions of the functions into this graph (i.e, 0 if x <= 0, 0 if x>=1). If this code can't be modified to take these two conditions into account, any other suggestions on code that could do this?

Upvotes: 1

Views: 131

Answers (1)

Sheldore
Sheldore

Reputation: 39042

You can use your condition as a mask and then make use of NumPy array indexing to assign the values of y to 0 for regions you want to.

Couple of changes:

  • I have used linspace to have a fine mesh so as to include more data points between x=0 and x=1. The range you were using generates integer so you will have basically a straight line between 0 and 1 otherwise.
  • y[(x<=0) | (x>=1)] = 0 is the key thing here. The | operator merges the two conditions (x<=0) | (x>=1) and returns indices from x-array where this condition holds True. Those indices are then used as an input to your y-array and then those values are assigned to 0.

I have restricted the x-limits to -1.5 to 1.5 so as to highlight the interesting region.

Complete answer for x^2 case

import numpy as np
import matplotlib.pyplot as plt
def graph(formula, x_range):
    x = np.array(x_range)
    y = eval(formula)

    y[(x<=0) | (x>=1)] = 0
    plt.plot(x, y)
    plt.xlim(-1.5,1.5)
    plt.show()

graph('x**2', np.linspace(-100, 100, 10000))

Plot for your actual equation

import numpy as np
import matplotlib.pyplot as plt

def graph(formula, x_range):
    x = np.array(x_range)
    y = eval(formula)

    y[(x<=0) | (x>=1)] = 0
    plt.plot(x, y)
    plt.xlim(-1.5,1.5)
    plt.show()

graph('(4/5)*(((x**4)/4)+x)', np.linspace(-100, 100, 10000))

enter image description here

enter image description here

Upvotes: 2

Related Questions