Python Function about Logistic Equation - python

The original logistic function that represents the change in population size per year is delta_N=r*(1-N/K)*N. I'm trying to write a new function that takes in r, K, N0 (The initial value of N, which stands for initial population size), and t (the number of years) and return the population N after t years. Below is my code. it does work but when I plug in t=0 (which is supposed to mean there is no change in time), it stills return some N that is different from N0 (which means my code is likely wrong?). Do people have any idea as to how I can fix my code?
def equation2(r,K,N0,t):
i=0
N=N0
while i<=t:
Nf=N+(r*(1-N/K)*N)
N=Nf
i=i+1
return Nf

I can see 2 potential problems with your code:
Plugging in t = 0 for your function will still go inside your while loop once because it will check for 0<=0 Which is true. You need to remove the = sign from your condition
After fixing this, Nf will be undefined when passing in t = 0. This also needs to be dealt with accordingly
def equation2(r,K,N0,t):
i=0
N=N0
while i<t:
N += (r*(1-N/K)*N)
i=i+1
return N

Related

how do i use For loop to calculate and print the sums from within the loop? Python

Hi all im brand new to programming obviously. As a part of my physics degree i have to do programming wonder if anyone can explain the following problem, this is not a piece of coursework or anything that i will be graded on so no im not cheating,im trying to speak to people who better understand this stuff who would like to explain to me the concept of my required task. The university seems to have restricted help available for this module so thought I'd ask the experts online.
In the cell below, by using the for loop, calculate and print the following sum (the sum of the square of first n natural numbers):
∑i = 1^2 + 2^2 + 3^2 + … + n^2,
where n=100 . (This means: loop over all numbers from 1 to 100, square each of them, and add them all together)
my current code is :
for n in range(0,101):
n = n**2
print(n)
#now this prints all the squared numbers but how do i tell it to add them all up? the sum function doesnt appear to work for this task. id appreciate any help! - JH
Almost there,
total = 0
for n in range(0,101):
total += n**2
print(total)
You missed the plus sign, you are just setting n to be the current number, you want to add it in every loop. So use a new variable called total and add into it.
The built-in sum() function is probably the best solution for this:
print(sum(x*x for x in range(1, 101)))
Output:
338350
You Can Simply Follow This Code
all_Sum = 0 #first create a variable to store all sum
#make a loop
for i in range(0,101): #making loop go from 0 to 100
all_Sum += i**2 #we are first getting square of number then added to variable
print(all_Sum) #printing all sum

i was watching Reducible's video about recursion and saw this code and i cant understand how it works could someone please explain?

# function counts number of ways you can
# partition n objects
# using parts up to m (assume m>=0)
n=int(input('enter n '))
m=int(input('enter m '))
def count(n, m):
if n==0:
return 1
elif m==0 or n<0:
return 0
else:
return count(n-m , m)+count(n , m-1)
print(count(n,m))
I don't understand the inputs and outputs of every function, I want to learn this and I am getting discouraged I hope someone could help I especially don't understand how it returns one value from this function, not two.
(this is my first post I don't know if it's the correct format).
I don't understand the inputs and outputs of every function
The inputs are the total number of objects n, and the maximum size of the partitions that it can be split into m.
The output is the count of the number of possible partitions fitting that criteria.
For instance, if n == 3 and m == 2, the possible partitions are 3 partitions with 1 item each, or 2 partitions with 2 and 1 items. So the output is 2.
I especially don't understand how it returns one value from this function, not two
The base cases clearly each return just a single value. One of them returns 1, the other returns 0.
If it doesn't return immediately from one of the base cases, it calls itself recursively twice, with smaller values of one of the parameters. So each recursive call gets closer to one of the base cases. When these return, it adds the results together, so it's only returning one value, not both values.

my code is giving me the wrong output sometimes, how to solve it?

I am trying to solve this problem: 'Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n^3, the cube above will have the volume of (n-1)^3 and so on until the top which will have a volume of 1^3.
You are given the total volume m of the building. Being given m can you find the number n of cubes you will have to build?
The parameter of the function findNb (find_nb, find-nb, findNb) will be an integer m and you have to return the integer n such as n^3 + (n-1)^3 + ... + 1^3 = m if such a n exists or -1 if there is no such n.'
I tried to first create an arithmetic sequence then transform it into a sigma sum with the nth term of the arithmetic sequence, the get a formula which I can compare its value with m.
I used this code and work 70 - 80% fine, most of the calculations that it does are correct, but some don't.
import math
def find_nb(m):
n = 0
while n < 100000:
if (math.pow(((math.pow(n, 2))+n), 2)) == 4*m:
return n
break
n += 1
return -1
print(find_nb(4183059834009))
>>> output 2022, which is correct
print(find_nb(24723578342962))
>>> output -1, which is also correct
print(find_nb(4837083252765022010))
>>> real output -1, which is incorrect
>>> expected output 57323
As mentioned, this is a math problem, which is mainly what I am better at :).
Sorry for the in-line mathematical formula as I cannot do any math formula rendering (in SO).
I do not see any problem with your code and I believe your sample test case is wrong. However, I'll still give optimisation "tricks" below for your code to run quicker
Firstly as you know, sum of the cubes between 1^3 and n^3 is n^2(n+1)^2/4. Therefore we want to find integer solutions for the equation
n^2(n+1)^2/4 == m i.e. n^4+2n^3+n^2 - 4m=0
Running a loop for n from 1 (or in your case, 2021) to 100000 is inefficient. Firstly, if m is a large number (1e100+) the complexity of your code is O(n^0.25). Considering Python's runtime, you can run your code in time only if m is less than around 1e32.
To optimise your code, you have two approaches.
1) Use Binary Search. I will not get into the details here, but basically, you can halve the search range for a simple comparison. For the initial bounds you can use lower = 0 & upper = k. A better bound for k will be given below, but let's use k = m for now.
Complexity: O(log(k)) = O(log(m))
Feasible range for m: m < 10^(3e7)
2) Use the almighty Newton-Raphson!! Using the iteration formula x_(n+1) = x_n - f(x_n) / f'(x_n), where f'(x) can be calculated explicitly, and a reasonable initial guess, let's say k = m again, the complexity is (I believe) O(log(k)) + O(1) = O(log(m)).
Complexity: O(log(k)) = O(log(m))
Feasible range for m: m < 10^(3e7)
Finally, I'll give a better initial guess for k in the above methods, also given in Ian's answer to this question. Since n^4+2n^3+n^2 = O(n^4), we can actually take k ~ m^0.25 = (m^0.5)^0.5. To calculate this, We can take k = 2^(log(k)/4) where log is base 2. The log should be O(1), but I'm not sure for big numbers/dynamic size (int in Python). Not a theorist. Using this better guess and Newton-Raphson, since the guess is in a constant range from the result, the algorithm is nearly O(1). Again, check out the links for better understanding.
Finally
Since your goal is to find whether n exists such that the equation is "exactly satisfied", use Newton-Raphson and iterate until the next guess is less than 0.5 from the current guess. If your implementation is "floppy", you can also do a range +/- 10 from the guess to ensure that you find the solution.
I think this is a Math question rather than a programming question.
Firstly, I would advise you to start iterating from a function of your input m. Right now you are initialising your n value arbitrarily (though of course it might be a requirement of the question) but I think there are ways to optimise it. Maybe, just maybe you can iterate from the cube root, so if n reaches zero or if at any point the sum becomes smaller than m you can safely assume there is no possible building that can be built.
Secondly, the equation you derived from your summation doesn't seem to be correct. I substituted your expected n and input m into the condition in your if clause and they don't match. So either 1) your equation is wrong or 2) the expected output is wrong. I suggest that you relook at your derivation of the condition. Are you using the sum of cubes factorisation? There might be some edge cases that you neglected (maybe odd n) but my Math is rusty so I can't help much.
Of course, as mentioned, the break is unnecessary and will never be executed.

Python repeating a function using the result of the previous function

I am a bit new to python and have been searching and trying different solutions to this issue.
I need to create a function that not only counts down within the function but also adds the previous results.
To help put this in context:
I have a formula for a weekly cost where Time corresponds to the current time within the model. It looks like the following:
week1 = 5000**((Time-1))
week2 = 5000**((Time-2))
...
(where the number next to time is increasing by one over a specific range)
Now the end result needs to be (for example)
if Time > 5:
return week1+ week2+ week3+ week4+ week5
elif Time == 5:
return week1+ week2+ week3+ week4
This would continue to time <=1. So I need a formula where not only is the function repeated a specific number of times adding the previous result, but one of the variables in the formula also changes based on the count. I know there must be an efficient way to do this with a loop but I can not seem to figure it out.
Any help would be amazing!
Thanks!
One way of solving this problem is using recursion. Put simply, it is a function that will continue to call itself until a specific condition is met (time <=1 in this example).
The downside of doing this is that it uses more memory than a simple loop.
An example of this would be:
def funcName(time):
sum = 0
if (time > 1):
sum = funcName(time-1)
sum += 5000**(time-1)
return sum
I think, your formula is wrong, it should be:
week1 = 5000 * (Time-1)
With simple loop:
result = 0
for i in range(Time):
result += 5000 * (Time - i)
print result
You can achieve it in one line using both sum and generator expression.
result = sum(5000 *(Time - i) for i in range(Time))

Fermat's little Theorem python

i am trying to implement Ferment's little Theorem via python. The value that returns does not give me a prime however. Any help is appreciated.
Apologies, the theorem states that in which for a random number of of times if a number is prime then any number generated less then it would give pow(a,value,x) == 1. The code below is an implementation of it.
The purpose of the code would be for function generate bit to create a 16 bit integer and run it via the theorem to prove if its a prime or not, if its a prime,return the value, if not call the function generatebit() again. Thank you for your time taken
import random
def generatebit():
x = random.getrandbits(16)
x = int(x)
if little(x):
return x
def little(x):
value = x -1
for i in xrange(50000):
# check for a total of 50000 times to reduce chances
a = random.getrandbits(15)
if pow(a,value,x) != 1:
generatebit()
break
return True
a=generatebit()
print a
Not knowing what the theorem is (see my comment), I can still tell you that there are some issues in your code.
you first call generatebits, which generates a random number. then if little(x), you return that value. Since however little(x) is always true, what this code does is create a random value and return it
Whatever happens within you for loop is totally without effect. all you do is assign a value to a variable a that never gets read, and call a function that returns a value you don't read

Categories

Resources