Creating step-wise function to increase x after given time intervals - python

I would like to create a step-wise increase in x starting from 0 and increasing by 10 every 30 seconds. I've defined time (t) as t=arange(0,120).
I looked at the Heaviside function but it did not seem to fit my need. I would need my x output to be a single value, not an array.
Sorry if this question is basic or misunderstood - I am very unfamiliar with python.

In order for you to set the value at n[0] to 0.29, n must be an array with something already at position 0.
n = [0.50] #already populated list
n[0] = 0.29
n = [0.29]
Alternatively, you could initialise the list with 0.29 as the first value.
n = [0.29]
n = [0.29]
As for your second question, we could use a for loop
import time #module used for time functions
for x in range(0, 120, 10): #defined a range of x (0,120) with a step of 10
print(x)
time.sleep(30) #wait 30 secs

Do you mean something like this?
import numpy
t=numpy.arange(0,120)
x=numpy.floor(t/30) * 10
It can also be done without numpy using list comprehension.
import math
t=range(0,120)
x=[math.floor(tx/30) * 10 for tx in t]
Or a traditional loop for that matter.
import math
x=[]
t=range(0,120)
for tx in t:
x.append(math.floor(tx/30) * 10)

Related

Sequentially take a window of rows from array (python)

I have an array of size nxm and want to take the first 10 rows and perform calculations, then take the next 10 rows perform calculations, etc. But this is hard coded, how can I make a loop?
Code Attempted:
import numpy as np
total = []
x= np.random.random((100,4))
a = np.average(x[:10])
total.append(a)
a = np.average(x[10:20])
total.append(a)
a = np.average(x[20:30])
....
Goal:
for *this array*:
# to something
# append value
# go back and get next 10 values
It looks like you want the following.
import numpy as np
x = np.random.random((100,4))
L = 10
k = 100//L
total = [np.average(x[L*i:L*(i+1)]) for i in range(k)]
If you'd rather implement this using a loop rather than list comprehension,
import numpy as np
x = np.random.random((100,4))
L = 10
k = 100//L
total = []
for i in range(k):
total.append(np.average(x[L*i:L*(i+1)]))
As an alternative, here's an approach using a 3-dimensional reshape.
x= np.random.random((100,4))
L = 10 #window length
n = x.shape[1] #number of columns
total = a.reshape(-1,10,n).mean(axis = (1,2))
import numpy as np
x = np.random.random((100,4))
a = 10
b = 100//a
c = 4
You want the array of average numbers of the first 10 * 4 part, the second 10 * 4 part,..., right?
reshape function can be really useful here.
x_splited = x.reshape((-1, a*c))
total = x_splited.mean(axis=1)
This is the answer you need. The reshape function let the first a*c elements in the original matrix become the first row of the new matrix. Then, mean(axis=1) help you get the average of the first row.
Also, you could try something like this:
x_splited = x.reshape((-1, a, c))
You can do something more complicated than this question with it.
Just a tip: in python, it is prefered to avoid using loop because it is slow.
Second tip: if you are still not proficient in using loop in Python, you are encouraged to spend some time to practice it.

How to do exponential growth in Python looped?

I was wondering if anyone could help me figure out how to do percentage addition in Python? I want to add exponential percentage growth to a given number i.e. 3% addition to 150 = 154.5, and then 3% to the new value but in a continuous string an x number of times.
like so:
1.) 150
2.) 154.5
3.) 159.135
4.) 163.90905
5.) 168.8263215
6.) 173.891111145
7.) 179.10784447935
8.) 184.4810798137305
9.) 190.0155122081424
10.) 195.7159775743867
Would love to be able to do this for 200 times and print in one go.
What I would do is:
Create a generator used to do the exponentional percentage:
def expo_generator(x):
while True:
yield x
x = x + x*3/100
Create a take utility (it takes n elements of a generator or array). (This util can be found also in more-itertools package)
from itertools import islice
def take(n, iterable):
return list(islice(iterable, n)
Then you can use:
result = take(20, expo_generator(150))
It will return an array of the first 20 value of the expo_generator function.
There are basically two ways to do it:
working with x in a loop:
x = 150
for n in range(200):
x *= 1.03 # multiplying by 103%, therefore "adding 3%"
print(x)
mathematical way:
x = 150
for n in range(200):
print(x * (1.03**n)) # a**b means a^b, exponetial function

How to have a function repeat itself multiple times?

so I want to generate 𝑛 random, floating-point numbers between 0 and 1 and calculate the mean. Then repeat this 𝑚 times. I want to do a Histogram with this later.
This is what I came up with so far:
import numpy as np
import matplotlib.pyplot as plt
import random
#random float number between 0 and 1
x=np.random.random(n)
print(np.mean(x))
#building my function
def myFunction(n,m):
for n in x:
return(np.mean(x))
print(myFunction(5,10))
So of course this will only give me one mean value, and my question is how can I build my function to repeat itself 𝑚 times?
You don't need any loops.
Instead of generating a random array of n elements m, times, make an n x m array and use numpy's API to take your mean along the second axis:
import numpy
m = 10
n = 5
x = numpy.random.random(size=(n, m))
means = x.mean(axis=1)
Your attempt is a bit off. You pass n to the function, but you also then do for n in x. So n is overwritten, but x is also a single number, so it won't iterate how you are wanting it to. For loops can be nested, so you can initialise two lists, one which will be the means of each run in m, and one which will store all the values in each run inside m to return the mean.
def myFunction(n,m):
mean_list = []
for _ in range(m):
inner_list = []
for i in range(n):
inner_list.append(np.random.random())
mean_list.append(np.mean(inner_list))
return mean_list
This returns a list of means, m means to be exact. So
myFunction(5, 10)
returns (as an example)
[0.6635917645438433, 0.5569813806972684, 0.5869406453209447, 0.48729391271790945, 0.6276934115328581, 0.6109176360963581, 0.45357579860009095, 0.611056289890255, 0.15579494695767637, 0.5097066251736436]
Please see the comments in the code below for an explanation:
import numpy as np
import matplotlib.pyplot as plt
import random
#Your function should contain a loop:
def myFunction(n,m):
# This loop is the "repeat M times" part. The variable "i"
# will count 0 to M - 1, a total of "M" iterations
for i in range(m):
#Everything inside here will run "M" times
x = np.random.random(n) # Here we generate N random numbers
mean = np.mean(x) #Here is the mean
#Print the means
print("Iteration {} mean: {}".format(i, mean))
myFunction(5,10) #Call it with N = 5 and M = 10
Your code doesn't work because return ends the function, you would have to either return a list of some sort or data container (1). Another alternative would be to run an outside loop with the parameters that you want(2).
ex. 1
def mf(m, n):
return np.mean(n)
data = []
for x in range(m):
data.append([x, mf(m, n)])
2
def mf(m, n):
data = []
for x in range(m):
data.append([x, np.mean(n)])
return data
There are some issues with your code.
First, since you created x outside of the function, it creates n random values just once and reuses the same x value resulting in the same mean.
Second, when you use return inside a for loop, it will stop the for loop and exit the function in the first iteration resulting in only one output.
A better way
import numpy as np # numpy has random module
import matplotlib.pyplot as plt
def myFunction(n,m):
list = []
for i in range(m):
x = np.random.rand(n)
list.append(np.mean(x))
return np.array(list)
# Even better way is to use list comprehension
def myFunction(n,m):
list = np.array([np.mean(np.random.rand(n)) for i in range(m)])
return list
You need to create the random array in the loop, so you get different random numbers each time.
The loop should collect all the results into a list, and return the list. You can do this using a list comprehension.
def myFunction(n,m):
return [np.mean(np.random(n)) for _ in range(m)]

amplitude spectrum in Python

I have a given array with a length of over 1'000'000 and values between 0 and 255 (included) as integers. Now I would like to plot on the x-axis the integers from 0 to 255 and on the y-axis the quantity of the corresponding x value in the given array (called Arr in my current code).
I thought about this code:
list = []
for i in range(0, 256):
icounter = 0
for x in range(len(Arr)):
if Arr[x] == i:
icounter += 1
list.append(icounter)
But is there any way I can do this a little bit faster (it takes me several minutes at the moment)? I thought about an import ..., but wasn't able to find a good package for this.
Use numpy.bincount for this task (look for more details here)
import numpy as np
list = np.bincount(Arr)
While I completely agree with the previous answers that you should use a standard histogram algorithm, it's quite easy to greatly speed up your own implementation. Its problem is that you pass through the entire input for each bin, over and over again. It would be much faster to only process the input once, and then write only to the relevant bin:
def hist(arr):
nbins = 256
result = [0] * nbins # or np.zeroes(nbins)
for y in arr:
if y>=0 and y<nbins:
result[y] += 1
return result

How to generate random variables and sum all them in python

My problem explicitly is
Z=sum_(i)^12 (x_i).
where i is indices and x_i's are random number...
I need an explicit code in Python to produce 12 random variables and sum all them.
I tried write code using if, while loop, but I could not get it.
I need your help...
In order to be able to use arbitrary variable just structure it as a function.
You can structure it similar to l82Munch, but this may be more readable for you since your just starting. Note that range is a generator function that returns a list up to the last call. So range(1,3) returns [1,2]
import random
def rand_sum(i, j):
sum_list = []
for rand_num in range(i, j+1):
sum_list.append(random.random()) # Check random docs for a function that returns
return sum(sum_list) # a different set of randoms if this isn't
# appropriate
import random
rand_sum = sum( random.random() for x in range(12) )
See the random documentation for more info.
In probabilistic modelling, you can define distributions then sum them.
Personally, I use OpenTURNS platform for that.
import openturns as ot
x1 = ot.Normal(0, 2) # Normal distribution mean = 0, std = 2
x2 = ot.Uniform(3, 5) # Uniform distribution between 3 and 5
sum = x1 + x2
That's it.
If x1,..., x12 are 12 distributions identically distributed you can write:
sum_12 = sum([x1] * 12)

Categories