Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pyplot lemniscate

i wonder if someone knows a more elegant way to plot a lemnicate in python (in terms of formula or other nice ideas are welcome). I fetched the formula from wikipedia. But wonder if it is possible to shorten the formular or so to make it more nice looking.

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
alpha = 1

#plot a lemniskate

t = np.linspace(0, 2*np.pi, num=1000) # 10^3 points 

x = [alpha * np.sqrt(2)*np.cos(i) / (np.sin(i)**2+1) for i in t]

y = [alpha * np.sqrt(2)*np.cos(i)*np.sin(i) / (np.sin(i)**2+1) for i in t]

plt.plot(x, y)

enter image description here

like image 972
PlagTag Avatar asked Apr 28 '26 14:04

PlagTag


1 Answers

Numpy arrays support "vectorized" operations. They're much faster and more memory-efficient than iterating through the array and creating a list from it.

Therefore, there's no need for the list comprehension in this case. It's better to operate on t directly.

For example:

import numpy as np
import matplotlib.pyplot as plt

alpha = 1
t = np.linspace(0, 2*np.pi, num=1000)

x = alpha * np.sqrt(2) * np.cos(t) / (np.sin(t)**2 + 1)
y = alpha * np.sqrt(2) * np.cos(t) * np.sin(t) / (np.sin(t)**2 + 1)

plt.plot(x, y)
plt.show()

Also, if you only want the shape, and don't care about the absolute values, you can omit the constants:

import numpy as np
import matplotlib.pyplot as plt

t = np.linspace(0, 2*np.pi, num=1000)

x = np.cos(t) / (np.sin(t)**2 + 1)
y = np.cos(t) * np.sin(t) / (np.sin(t)**2 + 1)

plt.plot(x, y)
plt.show()

enter image description here

like image 84
Joe Kington Avatar answered Apr 30 '26 06:04

Joe Kington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!