How can I plot this with numpy and matplotlib?
f(t) = t+2
, if t
is an integer
f(t) = 2**t
, otherwise
Say my function is defined just for t > 0
.
Is this possible to plot?
The approach I tried does not work... Not sure how to fix it.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from math import floor
# csfont = {'fontname':'Comic Sans MS'}
# hfont = {'fontname':'Helvetica'}
# plt.rcParams["font.family"] = "Comic Sans MS" # "Comic Sans MS"
font = {'family' : 'Comic Sans MS',
'weight' : 'bold',
'style' : 'italic',
'size' : 12}
matplotlib.rc('font', **font)
# a,b - the two ends of our interval
# [-16, 57]
a = 0.000001
b = 0.001
def f(t):
return ( t + 2 if (t==int(t)) else 2**t )
def g(x):
return np.floor(1/x)
t = np.linspace(a, b, 400)
f1 = f(t)
g1 = g(t)
plt.plot(t, f1, 'red', label="f (x)", linewidth=2) # plotting t, f1 separately
plt.plot(t, g1, 'green', label="g (x)", linewidth=2) # plotting t, g1 separately
plt.axhline(0, color='k')
plt.axvline(0, color='k')
# plt.xlabel('X axis', fontsize=14)
# plt.ylabel('Y axis', fontsize=14)
# plt.title("Illustration of the mean value theorem proof")
# plt.savefig('FFF.png')
plt.legend()
plt.show()
I also tried t==np.floor(t)
but this says: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I know why but that's not what I want. I just want to compute this function on that ndarray.