However, numpy does have efficient exponentiation in its `exp`

function. So we can transform the base to `e`

to use `exp`

by using

exp(-n * factor * log(2))

where `log`

is another numpy function and uses base `e`

. You could speed up your code even more by doing as much of the calculation as possible outside the loop that numpy sets up in its vectorization. In other words, you first set up the scalar

newfactor = -np.log(2) * factor

and set up your `x`

array using `x = np.linspace(0, 10, 1000000)`

or something similar. Then your `y`

array is created with

y = np.sin(x) * np.exp(newfactor * x)

**Code**

import numpy as np import numexpr as ne def orig(n_max, factor): n = np.arange(n_max) return np.sin(n) * 2 ** (-n * factor) #Rory Daulton 's solution def mod(n_max, factor): n = np.arange(n_max) newfactor = -np.log(2) * factor return np.sin(n) * np.exp(newfactor * n) def mod_2(n_max, factor): n = np.arange(n_max) return ne.evaluate("sin(n) * 2**(-n * factor)") #Rory Daulton 's solution using Numexpr def mod_3(n_max, factor): n = np.arange(n_max) newfactor = -np.log(2) * factor return ne.evaluate("sin(n) * exp(newfactor * n)")

**Timings**

% timeit res = orig(1e6, 0.5) 81 ms± 4.75 ms per loop(mean± std.dev.of 7 runs, 10 loops each) % timeit res = mod(1e6, 0.5) 46.3 ms± 5.29 ms per loop(mean± std.dev.of 7 runs, 10 loops each) % timeit res = mod_2(1e6, 0.5) 16 ms± 214 µs per loop(mean± std.dev.of 7 runs, 100 loops each) % timeit res = mod_3(1e6, 0.5) 11.1 ms± 48.4 µs per loop(mean± std.dev.of 7 runs, 100 loops each)

I'd like to create an array with a million anycodings_numpy numbers, that has a sine wave with anycodings_numpy exponential decay on the amplitude.,Now y is an array with all the anycodings_python calculated values corresponding to the anycodings_python values in the x array.,However, numpy does have efficient anycodings_python exponentiation in its exp function. So anycodings_python we can transform the base to e to use anycodings_python exp by using,What would be the most efficient way to do anycodings_numpy that?

However, numpy does have efficient anycodings_python exponentiation in its exp function. So anycodings_python we can transform the base to e to use anycodings_python exp by using

exp(-n * factor * log(2))

where log is another numpy function and anycodings_python uses base e. You could speed up your anycodings_python code even more by doing as much of the anycodings_python calculation as possible outside the loop anycodings_python that numpy sets up in its vectorization. anycodings_python In other words, you first set up the anycodings_python scalar

newfactor = -np.log(2) * factor

and set up your x array using x = anycodings_python np.linspace(0, 10, 1000000) or something anycodings_python similar. Then your y array is created anycodings_python with

y = np.sin(x) * np.exp(newfactor * x)

Code

import numpy as np import numexpr as ne def orig(n_max, factor): n = np.arange(n_max) return np.sin(n) * 2 ** (-n * factor) #Rory Daulton 's solution def mod(n_max, factor): n = np.arange(n_max) newfactor = -np.log(2) * factor return np.sin(n) * np.exp(newfactor * n) def mod_2(n_max, factor): n = np.arange(n_max) return ne.evaluate("sin(n) * 2**(-n * factor)") #Rory Daulton 's solution using Numexpr def mod_3(n_max, factor): n = np.arange(n_max) newfactor = -np.log(2) * factor return ne.evaluate("sin(n) * exp(newfactor * n)")

Timings

% timeit res = orig(1e6, 0.5) 81 ms Ã‚ Â± 4.75 ms per loop(mean Ã‚ Â± std.dev.of 7 runs, 10 loops each) % timeit res = mod(1e6, 0.5) 46.3 ms Ã‚ Â± 5.29 ms per loop(mean Ã‚ Â± std.dev.of 7 runs, 10 loops each) % timeit res = mod_2(1e6, 0.5) 16 ms Ã‚ Â± 214 Ã‚ Âµs per loop(mean Ã‚ Â± std.dev.of 7 runs, 100 loops each) % timeit res = mod_3(1e6, 0.5) 11.1 ms Ã‚ Â± 48.4 Ã‚ Âµs per loop(mean Ã‚ Â± std.dev.of 7 runs, 100 loops each)

Numpy has its own sin function, which is efficient at the task you want to do. The main cause of inefficiency would be in the exponentiation 2 ** (-n * factor).,However, numpy does have efficient exponentiation in its exp function. So we can transform the base to e to use exp by using,Numpy has efficient implementations for simple operations like sin(array), exp(array),.. The problem is that each expression (sin(n); -n * factor, 2 ** previous_Temp_array) is done on its own using temporary arrays for intermediate results. This leads to a quite high memory footprint and also has a negative impact on performance.,where log is another numpy function and uses base e. You could speed up your code even more by doing as much of the calculation as possible outside the loop that numpy sets up in its vectorization. In other words, you first set up the scalar

However, numpy does have efficient exponentiation in its `exp`

function. So we can transform the base to `e`

to use `exp`

by using

exp(-n * factor * log(2))

where `log`

is another numpy function and uses base `e`

. You could speed up your code even more by doing as much of the calculation as possible outside the loop that numpy sets up in its vectorization. In other words, you first set up the scalar

newfactor = -np.log(2) * factor

and set up your `x`

array using `x = np.linspace(0, 10, 1000000)`

or something similar. Then your `y`

array is created with

y = np.sin(x) * np.exp(newfactor * x)

**Code**

```
import numpy as npimport numexpr as nedef orig(n_max, factor): n = np.arange(n_max) return np.sin(n) * 2 ** (-n * factor) #Rory Daulton 's solutiondef mod(n_max,factor): n=np.arange(n_max) newfactor = -np.log(2) * factor return np.sin(n) * np.exp(newfactor * n)def mod_2(n_max,factor): n=np.arange(n_max) return ne.evaluate("sin(n) * 2**(-n * factor)")#Rory Daulton'
s solution using Numexprdef mod_3(n_max, factor): n = np.arange(n_max) newfactor = -np.log(2) * factor
return ne.evaluate("sin(n) * exp(newfactor * n)")
```

**Timings**

% timeit res = orig(1e6, 0.5) 81 ms± 4.75 ms per loop(mean± std.dev.of 7 runs, 10 loops each) % timeit res = mod(1e6, 0.5) 46.3 ms± 5.29 ms per loop(mean± std.dev.of 7 runs, 10 loops each) % timeit res = mod_2(1e6, 0.5) 16 ms± 214 µs per loop(mean± std.dev.of 7 runs, 100 loops each) % timeit res = mod_3(1e6, 0.5) 11.1 ms± 48.4 µs per loop(mean± std.dev.of 7 runs, 100 loops each)

To plot sine wave in python, we use NumPy library and Matplotlib library.,Step 1: Importing Libraries Code import numpy as np and import matplotlib.pyplot as plt are used to import numpy and matplotlib.pyplot Library. ,In this python program we use NumPy to generate time values and calculate sin(time) for sine data. And Matplotlib is used to handle plotting data and configuring plot attributes like label, grid etc.,NumPy is the fundamental package for scientific computing with Python. Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.

## Python Source Code: Sine Function

# Importing Required Libraries import numpy as np import matplotlib.pyplot as plt # Generating time data using arange function from numpy time = np.arange(-3 * np.pi, 3 * np.pi, 0.01) # Finding amplitude at each time amplitude = np.sin(time) # Plotting time vs amplitude using plot function from pyplot plt.plot(time, amplitude) # Settng title for the plot in blue color plt.title('Sine Wave', color = 'b') # Setting x axis label for the plot plt.xlabel('Time' + r '$\rightarrow$') # Setting y axis label for the plot plt.ylabel('Sin(time) ' + r '$\rightarrow$') # Showing grid plt.grid() # Highlighting axis at x = 0 and y = 0 plt.axhline(y = 0, color = 'k') plt.axvline(x = 0, color = 'k') # Finally displaying the plot plt.show()

Wikipedia, “Exponential function”, https://en.wikipedia.org/wiki/Exponential_function,This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.,A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.,Calculate the exponential of all elements in the input array.

```
>>>
import matplotlib.pyplot as plt
```

>>> x = np.linspace(-2 * np.pi, 2 * np.pi, 100) >>> xx = x + 1 j * x[: , np.newaxis] # a + ib over complex plane >>> out = np.exp(xx)

```
>>> plt.subplot(121) >>>
plt.imshow(np.abs(out),
...extent = [-2 * np.pi, 2 * np.pi, -2 * np.pi, 2 * np.pi], cmap = 'gray') >>>
plt.title('Magnitude of exp(x)')
```

```
>>> plt.subplot(122) >>>
plt.imshow(np.angle(out),
...extent = [-2 * np.pi, 2 * np.pi, -2 * np.pi, 2 * np.pi], cmap = 'hsv') >>>
plt.title('Phase (angle) of exp(x)') >>>
plt.show()
```

Same amplitudes and phases, but different frequencies yields to zero. Only when the steps are one or 0.5. It is because of the sampling rate.,A complex wave is a time series of imaginary numbers. As a such, it has a real part, and an imaginary part for every time. To visualized a complex wave, we can use a 3D representation. If we plot the imaginary part vs time, we will see a sine wave, and if we plot the real part vs time, we will see a cosine wave. Looking through the real axis you will see the cosine, and through the imaginary axis the sine.,If you try to compute the Fourier transform with only real-valued sines (or cosines), you will get a result that depends on the phase offset between the sine wave and the signal. Very little variation in phase would have differnt values.,With it, we have another convenient way to express an irrational number, because we have the angle ($k$), and the distancte to the origin ($m$).

```
In[1]:
%
pylab inline
```

% pylab inline

```
In [1]:
```%pylab inline

`Populating the interactive namespace from numpy and matplotlib`

% pylab inline

`Populating the interactive namespace from numpy and matplotlib`

In[3]: def mysine(t, amp, freq, phi): "" " Solves the sine wave equation; f(t;) = sin * 2 * np * freq * t + phi), where amp is the wave amplitude, freq is the wave frequency, phi is the phase shift, and t(time) the independent variable "" " return amp * np.sin(2 * np.pi * freq * t + phi)

def mysine(t, amp, freq, phi): "" " Solves the sine wave equation; f(t;) = sin * 2 * np * freq * t + phi), where amp is the wave amplitude, freq is the wave frequency, phi is the phase shift, and t(time) the independent variable "" " return amp * np.sin(2 * np.pi * freq * t + phi)

def mysine(t, amp, freq, phi): "" " Solves the sine wave equation; f(t;) = sin * 2 * np * freq * t + phi), where amp is the wave amplitude, freq is the wave frequency, phi is the phase shift, and t(time) the independent variable "" " return amp * np.sin(2 * np.pi * freq * t + phi)

```
In[4]:
dt = 1 / 30000 # sampling interval in sec
t = np.arange(0, 4, dt)
myparams = dict(amp = 4, freq = 1, phi = 0)
y = mysine(t, ** myparams)
plt.plot(t, y)
```

dt = 1 / 30000 # sampling interval in sec t = np.arange(0, 4, dt) myparams = dict(amp = 4, freq = 1, phi = 0) y = mysine(t, ** myparams) plt.plot(t, y)

```
Out[4]:
[<matplotlib.lines.Line2D at 0x7fdb84193240>]
```

Last Updated : 31 Jul, 2022

**Example:**

```
Input: n = 10
x = 30
Output: sum of sine series is 0.5
Input: n = 10
x = 60
Output: sum of sine series is 0.87
```

**Output:**

0.17