How to create logarithmic function with base x in python - python

I want to create a logarithmic function with base x then plot it: y=logx10.
So I use:
y= math.log(10,x)
but it returned an error said: only length-1 array can be converted to Python scalars.
So what is the correct way to create a log function with base x?

The simple way to get a "smoother" line is by increasing the number of points (i.e., make length bigger.)
Also, you likely want to sort your x list before calculating and plotting:
length = 100 # or higher
:
x = sorted([random.uniform(rand_min, rand_max) for r in xrange(length)])
y = [math.log(10, _x) for _x in x]

Since you want 2 lists of values (x, y), you will have to generate the x list first, and use it to generate the y list:
import math
import random
length = 10
rand_min = 0.02
rand_max = 0.91
x = [random.uniform(rand_min, rand_max) for r in xrange(length)]
y = [math.log(10, _x) for _x in x]
Here you have lists x and y, both of length length.

Related

finding gradient to specific x-value

I have a set of data in a numpy array - x-values, lets say between 0-100, and y-values. I need to get the gradient to a specific x-value ex. x=20 but I can only get the np.gradient function to give me the gradient at a certain index-value. right now I have:
g=np.gradient(y)
print(g[20])
but this of course gives me the gradient at i=20 and not x=20
I have both the x and y values in one 2D array and 2 x 1D arrays defined in my script
EDIT:
I actually came to solve it like this:
def grad(x, value):
def find_nearest(x, value):
x = np.asarray(Timeppmh)
idx = (np.abs(x - value)).argmin()
i = x.tolist().index(x[idx])
return i
g=np.gradient(yp,x)
find_nearest(x,value)
return g[find_nearest(x,value)]
If the value 20 is in x you could just do j[x == 20]. However, if that is not the case, you would need to approximate the gradient value. You can use for example linear interpolation.
import numpy as np
x = np.linspace(0, 100, 80)
print(20 in x) # 20 is not in x
# False
y = x * x + 3 * x + 2
# Pass x as second argument for value spacing
g = np.gradient(y, x)
print(np.interp(20, x, g)) # Should be 43
# 43.00000000000001

Plotting a graph given function definition

I'm currently trying to plot a graph of iterations of a certain function in python. I have defined the function as stated below but I am unsure on how to plot the graph such that the y value is on the y axis and the iteration number is on the x axis.
So, I have tried using the plt.plot function with different values in as my x values but using logistic(4, 0.7) as the y value for the y axis.
def logistic(A, x):
y = A * x * (1 - x)
return y
But each return an error. Can anyone shed any light on this, I want to do a total of 1000 iterations.
I dont understand much what you are saying concerning x being number ofiteration while you are showing us function logistic(4, 0.7). As far as I know, iterations is integer, whole number. You cant iterate just halfly or partially
def logistic(A, x):
y = A * x * (1 - x)
return y
A = 1
x_vals = []
y_vals = []
for x in range(1,1000):
x_vals.append(x)
y_vals.append(logistic(A,x))
#plt.plot(x_vals,y_vals) # See every iteration
#plt.show()
plt.plot(x_vals,y_vals) # See all iterations at once
plt.show()
Ah, the logistic map. Are you trying to make a cobweb plot? If so, your error may be elsewhere. As others have mentioned, you should post the error message and your code, so we can better help you. However, based on what you've given us, you can use numpy.arrays to achieve your desired result.
import numpy as np
import matplotlib.pyplot as plt
start = 0
end = 1
num = 1000
# Create array of 'num' evenly spaced values between 'start' and 'end'
x = np.linspace(start, end, num)
# Initialize y array
y = np.zeros(len(x))
# Logistic function
def logistic(A, x):
y = A * x * (1 - x)
return y
# Add values to y array
for i in range(len(x)):
y[i] = logistic(4, x[i])
plt.plot(x,y)
plt.show()
However, with numpy.arrays, you can omit the for loop and just do
x = np.linspace(start, end, num)
y = logistic(4, x)
and you'll get the same result, but faster.

Integrating numerical data with scipy

Basically I have 2 arrays obtained from a set of data points one array for the x values and one for the y values. I need to numerically integrate the y values with respect to the x values - i.e. an element from the y integrated with respect to the corresponding element in x. This should then generate a new array of elements. I have tried simpson's rule but I get one value back instead of an array. A general idea or approach is all I'm looking for. Any help, however, will be much appreciated.
Thanks.
# check out this:
def integration_by_simpsons_3_8_th_rule(i,X,Y,Fd):
h = X[i]-X[i-1]
y_n = Y[i]
y_n_1 = signal[i-1]
y_n_2 = signal[i-2]
y_n_3 = signal[i-3]
Area = (3/8)*h*( y_n_3 + 3*(y_n_2 + y_n_1) + y_n )
return (X[i-1],Area)
def rolling_integration(X,Y,Fd):
Y_int = []
corres_X = []
for i in range(3,len(signal),1):
x,y = integration_by_simpsons_3_8_th_rule(i,X,Y,Fd)
Y_int.append(float(y))
corres_X.append(float(x))
return (np.array(corres_X)+(np.array(1/(4*float(Fd)))),np.array(Y_int))
#Fd : for phase correction

2D array with numpy

I have written the following code for creating a 2D array and filing the first element of each row. I am new to numpy. Is there a better way to do this?
y=np.zeros(N*T1).reshape(N,T1)
x = np.linspace(0,L,num = N)
for k in range(0,N):
y[k][0] = np.sin(PI*x[k]/L)
Yes, since numpy vectorizes operations, you can just do:
y[:,0] = np.sin(np.pi * x / L)
Note that y[:,0] grabs the first column of y (the : in the first coordinate essentially means "grab all rows", and the 0 in the second coordinate means "from the column at index 0" (ie the first column)). Since np.sin(np.pi * x / L) is also an array, you can assign the latter to the former directly.
This question is rather for codereview#stackexchange, but this snippet works!
import numpy as np
N = 1000 # arbitrary
T1 = 1000 # arbitrary
L = 10 # arbitrary
x = np.linspace(0,L,num = N)
# you don't need reshape here, give the size as a tuple!
y = np.zeros((N,T1))
# use a vectorized call here:
y[:,0] = np.sin(np.pi*x/L)

Get vector space coordinates from symbolic polynomial

I'm trying to get the vector coordinates from the polynomial p in the follow code assuming that x,y and z belong to GF(2) but I get error
TypeError: can't initialize vector from nonzero non-list.
How I will be able to fix that?
reset()
var("x")
var("y")
var("z")
pp = 2
k.<t>=GF(2^pp)
VS = k.vector_space()
p = z*x*t^2 + t*y + 1
print VS.coordinates(p)
Maybe you can use the coefficient list of the polynomial as its vectoral coordinates, and then you may convert this list to a vector. But in that case, it is better to define GF(2^2) as GF(4,'a')={0,1,a,a+1}.
For example you may do something like this:
sage
K = GF(4,'a')
R = PolynomialRing(GF(4,'a'),"x")
x = R.gen()
a = K.gen()
p = (a+1)*x^3 + x^2 + a
p.list()
If you need to fix the dimension n to a bigger value than the degree of p, then you may do the following;
n = 6
L = p.list(); l=len(L); i = n-l; L_ = [0]*i; L.extend(L_)
L
gives you the 6-dimensional coordinates of p.
If you need to use this coefficient list as a vector afterwards, you may just use vector(L) instead of L.

Categories