'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



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1