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
Related
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)
x is my input.
I need to find i,j>=0 and n,m>1 such as x = i**m+j**n
For now I have been doing this , but it is way to slow !! How can I improve it ?
from math import sqrt
import numpy as np
def check(x):
for i in range(1,int(np.ceil(sqrt(x)))):
for j in range(1,int(np.ceil(sqrt(x)))):
for m in range(2,x/2+1):
for n in range(2,x/2+1):
if((pow(i,m) +pow(j,n))==x):
print 'Yes';
return ;
print 'No';
thank you !
You could reverse the process, by finding all powers (i**m) smaller than x. Then you just check if any pair of these powers adds up to x.
def check(x):
all_powers = set([1]) #add 1 as a special case
#find all powers smaller than x
for base in range(2,int(math.ceil(sqrt(x)))):
exponent = 2;
while pow(base, exponent) < x:
all_powers.add(pow(base, exponent))
exponent+=1
#check if a pair of elements in all_powers adds up to x
for power in all_powers:
if (x - power) in all_powers:
print 'Yes'
return
print 'No'
The code above is simple but can be optimized, e.g., by integrating the check if a pair adds up to x in the while loop you can stop early in most cases.
From time to time a question pops up here about determining if a positive integer is the integral power of another positive integer. I.e. given positive integer z find positive integers j and n such that z == j**n. This can be done in time complexity O(log(z)) so it is fairly fast.
So find or develop such a routine: call it is_a_power(z) which returns a tuple (j, n) if z is such a power of (0, 0) if it is not. Then loop over i and m, then check if x - i**m is a power. When it becomes one, you are done.
I'll let you finish the code from here, except for one more pointer. Given x and i where i > 1, you can find the upper limit on m such that i**m <= x with
m <= log(x) / log(i)
Note that i == 1 is a special case, since i**m does not actually depend on m in that case.
from math import sqrt
import numpy as np
def build(x):
# this function creates number that are in form of
# a^b such that a^b <= x and b>1
sq=sqrt(x);
dict[1]:1; # 1 is always obtainable
dict[0]:1; # also 0 is always obtainable
for i in range(1,sq): # try the base
number=i*i; # firstly our number is i^2
while number<=x:
dict[number]:1; # this number is in form of a^b
number*=i; # increase power of the number
def check(x):
sq=sqrt(x);
for i in range(1,sq): # we will try base of the first number
firstnumber=1;
while firstnumber<=x: # we are trying powers of i
remaining=x-firstnumber; # this number is remaining number when we substract firstnumber from x
if dict[remaining]==1: # if remaining number is in dictionary which means it is representable as a^b
print("YES"); # then print YES
return ;
firstnumber*=i; # increase the power of the base
print("NO");
return ;
Above code works in O( sqrt(x) * log(x) * log(x) ) which is faster.
You can read comments in code to understand it.
I am unsure of how to create the loop to keep dividing the number by two? Please help. I know you you can divide a number by 2 don't know how to create the loop to keep dividing until it is less than 1.0.
It depends on what exactly you're after as it isn't clear from the question. A function that just divides a number by zero until it is less than 1.0 would look like this:
def dividingBy2(x):
while x > 1.0:
x = x/2
But this serves no purpose other than understanding while loops, as it gives you no information. If you wanted to see how many times you can divide by 2 before a number is less than 1.0, then you could always add a counter:
def dividingBy2Counter(x):
count = 0
while x > 1.0:
x = x/2
count = count + 1
return count
Or if you wanted to see each number as x becomes increasingly small:
def dividingBy2Printer(x):
while x > 1.0:
x = x/2
print(x)
b=[] #initiate a list to store the result of each division
#creating a recursive function replaces the while loop
#this enables the non-technical user to call the function easily
def recursive_func(a=0): #recursive since it will call itself later
if a>=1: #specify the condition that will make the function run again
a = a/2 #perform the desired calculation(s)
recursive_func(a) #function calls itself
b.append(a) #records the result of each division in a list
#this is how the user calls the function as an example
recursive_func(1024)
print (b)
I have a function shown below
f(t) = 1 : if 2t rounded down to the next lowest integer is even
f(t) = -1 : if 2t rounded down to the next lowest integer is odd
I am trying to eventually carry out fourier transformations on the function but first I need to write a program to create an array of N=1000 elements containing 1000 equally spaced samples from a single cycle of this function which is a square wave.
How do I create this array ?
As you ask for the values of the square function within a cycle, first you have to create the values for the time samples. Starting at t=0 the function you mentioned has a cycle of 1, after t=1 the function repeates itself.
For creating a sequence of equally spaced values between 0 and 1 there are several alternatives, but a straitght one is numpy.linspace. The first parameter is the starting time of the cycle, the second the end of the cycle and the third the number of samples (equally spaced). By using this you create the t_samples.
After that you just need to feed the square wave function (square_func in the code below) with the values stored in t_samples.
See an example here of how you can use it:
import numpy
def square_func(t):
if int(2*t)%2 == 0:
return 1
else:
return -1
t_samples = numpy.linspace(0.0,1.0,1000)
samples = [square_func(i) for i in t_samples]
The variable samples stores a list with the values you need (half of them are '1s' and the other half '-1s', as we are referring to one cycle). The cycle of the function produced with this code is shown in the following figure:
The function can be defined this way.
def f(t):
return 1 if int(2 * t) % 2 == 0 else -1
And if you are using python 2.x you can use map to create the list.
N = 1000
sample = map(f, xrange(N)) # Or alternatively map(lambda n: f(n), xrange(N))
Let's assume you have a method returning the sample value:
import math
def f(t):
"""
f(t) = 1 if ⌊2t⌋ is even, −1 if ⌊2t⌋ is odd
"""
if math.floor(2 * t) % 2 == 0:
return 1
else:
return -1
The easiest way to generate your array would be to do:
a = [f(n) for n in xrange(1000)]
Note: This assumes Python 2.x, use range if Python 3.x
I ended up answering it in this way
F=zeros(1000)
F[0:500]=1
F[500:1000]=-1
Is there a pythonic way to build up a list that contains a running average of some function?
After reading a fun little piece about Martians, black boxes, and the Cauchy distribution, I thought it would be fun to calculate a running average of the Cauchy distribution myself:
import math
import random
def cauchy(location, scale):
p = 0.0
while p == 0.0:
p = random.random()
return location + scale*math.tan(math.pi*(p - 0.5))
# is this next block of code a good way to populate running_avg?
sum = 0
count = 0
max = 10
running_avg = []
while count < max:
num = cauchy(3,1)
sum += num
count += 1
running_avg.append(sum/count)
print running_avg # or do something else with it, besides printing
I think that this approach works, but I'm curious if there might be a more elegant approach to building up that running_avg list than using loops and counters (e.g. list comprehensions).
There are some related questions, but they address more complicated problems (small window size, exponential weighting) or aren't specific to Python:
calculate exponential moving average in python
How to efficiently calculate a running standard deviation?
Calculating the Moving Average of a List
You could write a generator:
def running_average():
sum = 0
count = 0
while True:
sum += cauchy(3,1)
count += 1
yield sum/count
Or, given a generator for Cauchy numbers and a utility function for a running sum generator, you can have a neat generator expression:
# Cauchy numbers generator
def cauchy_numbers():
while True:
yield cauchy(3,1)
# running sum utility function
def running_sum(iterable):
sum = 0
for x in iterable:
sum += x
yield sum
# Running averages generator expression (** the neat part **)
running_avgs = (sum/(i+1) for (i,sum) in enumerate(running_sum(cauchy_numbers())))
# goes on forever
for avg in running_avgs:
print avg
# alternatively, take just the first 10
import itertools
for avg in itertools.islice(running_avgs, 10):
print avg
You could use coroutines. They are similar to generators, but allows you to send in values. Coroutines was added in Python 2.5, so this won't work in versions before that.
def running_average():
sum = 0.0
count = 0
value = yield(float('nan'))
while True:
sum += value
count += 1
value = yield(sum/count)
ravg = running_average()
next(ravg) # advance the corutine to the first yield
for i in xrange(10):
avg = ravg.send(cauchy(3,1))
print 'Running average: %.6f' % (avg,)
As a list comprehension:
ravg = running_average()
next(ravg)
ravg_list = [ravg.send(cauchy(3,1)) for i in xrange(10)]
Edits:
Using the next() function instead of the it.next() method. This is so it also will work with Python 3. The next() function has also been back-ported to Python 2.6+.
In Python 2.5, you can either replace the calls with it.next(), or define a next function yourself.
(Thanks Adam Parkin)
I've got two possible solutions here for you. Both are just generic running average functions that work on any list of numbers. (could be made to work with any iterable)
Generator based:
nums = [cauchy(3,1) for x in xrange(10)]
def running_avg(numbers):
for count in xrange(1, len(nums)+1):
yield sum(numbers[:count])/count
print list(running_avg(nums))
List Comprehension based (really the same code as the earlier):
nums = [cauchy(3,1) for x in xrange(10)]
print [sum(nums[:count])/count for count in xrange(1, len(nums)+1)]
Generator-compatabile Generator based:
Edit: This one I just tested to see if I could make my solution compatible with generators easily and what it's performance would be. This is what I came up with.
def running_avg(numbers):
sum = 0
for count, number in enumerate(numbers):
sum += number
yield sum/(count+1)
See the performance stats below, well worth it.
Performance characteristics:
Edit: I also decided to test Orip's interesting use of multiple generators to see the impact on performance.
Using timeit and the following (1,000,000 iterations 3 times):
print "Generator based:", ', '.join(str(x) for x in Timer('list(running_avg(nums))', 'from __main__ import nums, running_avg').repeat())
print "LC based:", ', '.join(str(x) for x in Timer('[sum(nums[:count])/count for count in xrange(1, len(nums)+1)]', 'from __main__ import nums').repeat())
print "Orip's:", ', '.join(str(x) for x in Timer('list(itertools.islice(running_avgs, 10))', 'from __main__ import itertools, running_avgs').repeat())
print "Generator-compatabile Generator based:", ', '.join(str(x) for x in Timer('list(running_avg(nums))', 'from __main__ import nums, running_avg').repeat())
I get the following results:
Generator based: 17.653908968, 17.8027219772, 18.0342400074
LC based: 14.3925321102, 14.4613749981, 14.4277560711
Orip's: 30.8035550117, 30.3142540455, 30.5146529675
Generator-compatabile Generator based: 3.55352187157, 3.54164409637, 3.59098005295
See comments for code:
Orip's genEx based: 4.31488609314, 4.29926609993, 4.30518198013
Results are in seconds, and show the LC new generator-compatible generator method to be consistently faster, your results may vary though. I expect the massive difference between my original generator and the new one is the fact that the sum isn't calculated on the fly.