Equation
This link goes to the picture of the equation i am trying to graph in matplotlib
from matplotlib import pyplot as plt
import numpy as np
x_values = np.arange(1, 10, step=0.1)
y_values = (np.arcsin(np.sqrt(abs(np.sin(x_values) ** (abs(np.cos(x_values)) + abs(np.sin(x_values)) + (2.718281828459045** np.sin(x_values)))))) - x_values)/x_values
The code above throws the following error message:
ipykernel_launcher.py:4: RuntimeWarning: invalid value encountered in power
after removing the cwd from sys.path.
I didn't get to the plotting because this code alone threw an error message
How can i fix this?
numpy does not allow fractional powers of negative numbers, since it expects a complex result and you did not define a complex type. You can inspect your power array like this:
pow = abs(np.cos(x_values)) + abs(np.sin(x_values)) + (2.718281828459045** np.sin(x_values))
a = np.sin(x_values)
and use a workaround like this:
a_pow = np.sign(a) * (np.abs(a)) ** (pow)
y_values = (np.arcsin(np.sqrt(abs(a_pow))) - x_values)/x_values
But make sure in advance that you are not expecting complex numbers as results!
If you do though, change your array dtype to np.complex.
Related
I got a simple 2D array of values like this :
[simple array]
and I want to add reverb to it (I don't know how to call it other way) in order for it to look like this, basicly with a damping/smooth effect on y values but only on +x :
[with reverb]
I tried to check with scipy as i'm already using it to smooth values but didn't found out how to do it.
does anybody has an idea ?
You could try a Finite impulse response filter, though it's not clear if it's exactly what you need.
This was produced by the script below.
I've assumed, given your figures, that your data is actually 1-dimensional (a "line" of numbers, not a "rectangle").
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
npts = 50
# FIR with falling sawtooth impulse response
b = np.linspace(1,0,npts,endpoint=False)
u = np.zeros(3 * npts)
u[0] = 1
u[npts + 10] = 1
u[npts + 10 + npts//2] = 1
y = signal.lfilter(b, [1], u)
fig, ax = plt.subplots(2)
ax[0].stem(u)
ax[0].set_ylabel('input')
ax[1].stem(y)
ax[1].set_ylabel('output')
plt.show()
I need a plot which doesn't fit the usual 'log-log' definition, but has a linear x scale and a double logarithmic y scale. I tried to create this in matplotlib with
import numpy as np
from matplotlib import pyplot as plt
# constants that result from other part of program
b = 9.144
c = -3.579
# values for plot
XL = np.linspace(273.15,373.15,101)
YL = 10 ** 10 ** (b + c * np.log10(XL)) - 0.7
# functions for scale transformation
def fw(x):
return np.log10(np.log10(x))
def bw(x):
return 10 ** 10 ** x
plt.plot(XL - 273.15, YL)
plt.yscale('function', functions=(fw, bw))
plt.show()
Please find this image for reference. However this program has two problems:
The y axis ticks start at 100 for a reason that I do not understand, leaving the largest part of the graph without any ticks.
I get the following warnings from NumPy regarding the log10 calls from fw(x):
RuntimeWarning: divide by zero encountered in log10
return np.log10(np.log10(x))
RuntimeWarning: invalid value encountered in log10
return np.log10(np.log10(x))
I get that probably the first warning leads to the second, but I do not see why there would be a division by zero. Any assistance to enlightenment on both problems would be greatly appreciated.
According to Python Documentation a TypeError is defined as
Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.
exception TypeError
The reason I got this Error was because my code looked like this:
import math as m
import pylab as pyl
import numpy as np
#normal distribution function
def normal(x,mu,sigma):
P=(1/(m.sqrt(2*m.pi*sigma**2)))*(m.exp((-(x-mu)**2)/2*sigma**2))
return P
#solution
x = np.linspace(-5,5,1000)
P = normal(x,0,1)
#plotting the function
pyl.plot(x,P)
pyl.show()
P=(1/(m.sqrt(2***m**.pisigma2)))(**m.exp((-(x-mu)2)/2*sigma2))
Notice the m. - This is incorrect, because math. can only handle scalars. And the Error said that a TypeError had occurred.
np. (Numpy) can handle scalers as well as arrays and the problem is solved.
The right code looks like this:
import math as m
import pylab as pyl
import numpy as np
# normal distribution function
def normal(x,mu,sigma):
P = (1/(np.sqrt(2*np.pi*sigma**2))) * (np.exp((-(x-mu)**2)/2*sigma**2))
return P
# solution
x = np.linspace(-5,5,1000)
P = normal(x,0,1)
# plotting the function
pyl.plot(x,P)
pyl.show()
In the end we get a great normal distribution function that looks like this:
This Error occurred in Spyder IDE.
I'm trying to replicate some Matlab code into Python and at the moment im developing a unit test to check for equivalence. In the code below I get errors in the order of E-11 which indicates to me that it could possibly be a rounding error.
Matlab Code:
width = 200;
x = 1:100000;
b = ones(width,1)/width;
y = filter(b, 1, x);
save('mat_data')
Python Code:
import numpy as np
from scipy.io import loadmat
from scipy import signal
def plot_fig(x, y=None):
import matplotlib.pyplot as plt
if y is None:
y = x
x = np.arange(0, len(y))
plt.figure()
plt.plot(x, y)
plt.show()
def mat_data(param):
data = loadmat('mat_data.mat')
return np.squeeze(data[param])
y = signal.lfilter(mat_data('b'), 1, mat_data('x'), axis=0)
plot_fig(mat_data('y') - y)
I have used the loadmat function to ensure equivalence between the numerical arrays I use as function inputs. The resulting plot is:
difference plot
I see that the error is small, so could be rounding errors, but it does also seem to accumulate which worries me.
At the moment the application I'm working on is critical to ensure the binary equivalence between the two codes (matlab and python) so I would greatly appreciate any help in resolving this disparity.
Thanks in advance,
A.
You could try double precision floats rather than single precision in python.
I think that would reduce accumulating rounding error significantly.
import scipy.io.wavfile as wav
import matplotlib.pyplot as plt
import scipy
sample_rate, X = wav.read("/Users/sinaastani/Downloads/partynextdoor.wav")
X = scipy.mean(X, axis=1)
plt.specgram(X, Fs=sample_rate, xextent=(0,30))
I get an error whenever I run the code above:
/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/matplotlib/axes/_axes.py:7017: RuntimeWarning: divide by zero encountered in log10
Z = 10. * np.log10(spec)
This occurs with several wav files that I have tried. I'm simply trying to replicate an example from "Building Machine Learning Systems with Python - Second Edition".
The wavfile.read function returns a numpy array. It looks like at the beginning and end of this array, there are a bunch of 0 values so when it tries to calculate log(0) it is undefined. What is the appropriate to deal with this? Should I simply get rid of 0 values from the array?
Use the parameter NFFT of plt.specgram(). Because this parameter defaults to 256, it causes the error. You can increase this number by multiplying it to 2 to the extent by which the error disappears. Try 512 - 1024 - 2048 , ... and the problem is solved!:)