My question is: Why do these two programs provide different answers! Thank you in advance!
I created two programs that find the value of pi as close as possible based off of the user input for the total sum. However, I created two programs one that steps by 2 and one that steps by 4. I was wondering why the answers provided by the two codes are different.
Code that uses 2 step.
import math
total = 0
def main():
#input
n = int(input("How many numbers are we going to process: "))
#process
#initialize total
total = 0
#create the loop that runs via amount input
for i in range(0, n , 2):
total = total + ( 1 / ((i * 2) + 1)) - (1 / ((i * 2) + 3))
amount = total * 4
print(amount)
print("In comparison to pi the value is: ", (math.pi - amount))
main()
Code that uses 4 step
import math
total = 0
def main():
#input
n = int(input("How many numbers are we going to process: "))
#process
#initialize total
total = 0
#create the loop that runs via amount input
for i in range(0, n , 4):
total = total + ( 1 / ((i * 2) + 1)) - (1 / ((i * 2) + 3)) + (1/
((i * 2) + 5)) - (1/ ((i * 2) + 7))
amount = total * 4
print(amount)
print("In comparison to pi the value is: ", (math.pi - amount))
main()
Related
I am trying to make clusters of sites based on their distance from each other. I am using or tools cp solver to achieve this. The program runs fine for 40 to 50 number of sites but when i try to run for about 200 sites with each cluster containing 10 sites the program gets stuck and does not give any output. I am using the cp_model for this.
Please below the code I am using :
from ortools.sat.python import cp_model
import pandas as pd,sys,os,requests,re
matrix_data = pd.read_csv(''.join([filepath,'//matrix.csv']),
matrix = matrix_data.values.tolist()
#data = {}
#data['distance_matrix'] = []
distance_matrix = []
for i in matrix:
distance_matrix.append(i)
def main():
"""Entry point of the program."""
num_nodes = len(distance_matrix)
print('Num nodes =', num_nodes)
# Number of groups to split the nodes, must divide num_nodes.
num_groups = 10
# Model.
model = cp_model.CpModel()
# Variables.
neighbors = {}
obj_vars = []
obj_coeffs = []
for n1 in range(num_nodes - 1):
for n2 in range(n1 + 1, num_nodes):
same = model.NewBoolVar('neighbors_%i_%i' % (n1, n2))
neighbors[n1, n2] = same
obj_vars.append(same)
obj_coeffs.append(distance_matrix[n1][n2] + distance_matrix[n2][n1])
# Number of neighborss:
for n in range(num_nodes):
model.Add(sum(neighbors[m, n] for m in range(n)) +
sum(neighbors[n, m] for m in range(n + 1, num_nodes)) ==
group_size - 1)
# Enforce transivity on all triplets.
for n1 in range(num_nodes - 2):
for n2 in range(n1 + 1, num_nodes - 1):
for n3 in range(n2 + 1, num_nodes):
model.Add(
neighbors[n1, n3] + neighbors[n2, n3] + neighbors[n1, n2] != 2)
# Redundant constraints on total sum of neighborss.
model.Add(sum(obj_vars) == num_groups * group_size * (group_size - 1) // 2)
# Minimize weighted sum of arcs.
model.Minimize(
sum(obj_vars[i] * obj_coeffs[i] for i in range(len(obj_vars))))
# Solve and print out the solution.
solver = cp_model.CpSolver()
solver.parameters.log_search_progress = True
solver.parameters.num_search_workers = 6
status = solver.Solve(model)
print(solver.ResponseStats())
visited = set()
for g in range(num_groups):
flonglist = []
flatlist = []
for n in range(num_nodes):
if not n in visited:
visited.add(n)
output = str(n)
for o in range(n + 1, num_nodes):
if solver.BooleanValue(neighbors[n, o]):
visited.add(o)
output += ' ' + str(o)
print('Group', g, ':', output)
print(site_list)
break
if __name__ == '__main__':
main()
print("-- %s seconds ---" % (time.time() - start_time))
The matrix file contain the distance of sites from each other in matrix format.
need some help.
Is there a faster way to create an exponential moving average than for loop?
I am priming the first n values of exp_aves to be mean of first n obseravtions.
def exp_mov_ave(observations, n):
exp_ave = np.mean(observations[0:n])
lambdak = (n - 1) / (n + 1)
exp_aves = []
for i,element in enumerate(observations):
if (i >= n):
exp_ave = (lambdak * exp_ave) + ((1 - lambdak) * element)
exp_aves.append(exp_ave)
return np.array(exp_aves)
I tried running the program below:
from functools import lru_cache
#lru_cache(Maxsize = None)
def count(n):
factorial_num = 1
num_digits = 0
if n == 1:
factorial_num = 1
else:
factorial_num = n * count(n-1)
return len(str(factorial_num))
However, it didn't give me the length of the factorial number as anticipated.
I also wanted to use the code to find the factorial of very big numbers in range of billions and tried using lru_cache. Still, no luck.
As Aziz pointed out in the comments, your recursive case is wrong.
factorial_num = n * count(n-1)
This would do something useful if count(n-1) actually returned (n-1)!, but it doesn't, since you're trying to return a digit count instead.
>>> count(1)
1 # Base case is correct.
>>> count(2)
1 # 2 * count(1) = 2 * 1 = 2. Whose *length* is 1 digit.
>>> count(9)
1 # For all single-digit n, count(n) is still 1.
>>> count(10)
2 # 10 * count(9) = 10 * 1 = 10. Whose *length* is 2 digits.
You should write a function that just calculates the factorial, instead of trying to mix this logic with the digit counting.
#lru_cache(maxsize=None)
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
Note that recent versions of Python have a built-in math.factorial function, which you could use instead if your teacher is not requiring you to roll your own factorial code.
Then, you can simply use len(str(factorial(n))) to count the digits.
You can use Kamenetsky formula to return the number of digits in n!
For minor numbers use:
def findDigits(n):
if (n < 0):
return 0;
if (n <= 1):
return 1;
digits = 0;
for i in range(2, n + 1):
digits += math.log10(i);
return math.floor(digits) + 1;
For bigger numbers use:
def findDigits(n):
if (n < 0):
return 0;
if (n <= 1):
return 1;
x = ((n * math.log10(n / math.e) +
math.log10(2 * math.pi * n) /2.0));
return math.floor(x) + 1;
source: https://www.geeksforgeeks.org/count-digits-factorial-set-1/?ref=lbp and https://www.geeksforgeeks.org/count-digits-factorial-set-2/?ref=lbp
lope = []
def main():
print('This program is going to do 5 calculations for growth rates on FCF.')
growth = .10
freecash = int(input('What is initial free cash flow'))
for i in range(5):
freecash = freecash * (1+growth)
lope.append(freecash)
equation = freecash * (1+.03)
print('The value in of Free cash in 5 years is: ',equation)
# this next part is for calculating the terminal
print('This Calculates the terminal for you.')
bwacc = float(input('Whats the WACC: '))
# ltg == Long Term Growth
ltg = .03
equation1 = equation * (1+ltg)/(bwacc-ltg)
print('The Terminal Value is: ',equation1)
one = lope[0] / (1+bwacc) ** 1
two = lope[1] / (1+bwacc) ** 2
three = lope[2] / (1+bwacc) ** 3
four = lope[3] / (1+bwacc) ** 4
five = lope[4] / (1+bwacc) ** 5
print('The pv of perpetuity is: ',one, two,three,four,five)
This code is meant to calculate these 5 equations in the last 5 lines of code, I'm not really understanding how this isn't working when I put print statements.
The best way would be to use a loop:
list4numbers = []
for i in range(5):
a = lope[i] / (1+bwacc) ** i+1
list4numbers.append(a)
With this you could do what ever you needed with the list. Hope I helped!
-Zeus
px = 1 + x ** 2
cx = x ** 0
fx = (-5 / 16) * (1 / x ** (3 / 4)) - (29 / 16) * x ** (5 / 4)
newmann_g0 = "none"
newmann_gl = 2.5
dirichlet_u0 = 0
dirichlet_ul = "none"
# Deciding if it is uniform or geometric and finding the Nod Point & Mesh
length = 0.1
num_element = int(1 / length)
num_nod_point = num_element + 1
degree = [3 for i in range(num_element)]
nod_point = [0]
for i in range(1, num_element + 1):
nod_point += [i * length]
h = [length for _ in range(1, num_nod_point)]
max_degree = max(degree)
# Finding the Legendre Polynomial by iteration
legendre_poly = [1, x]
for n in range(1, max_degree):
legendre_poly.append(x * legendre_poly[n] * (2 * n + 1) / (n + 1) - legendre_poly[n - 1] * n / (n + 1))
# Calculating the Shape Function by iteration
shape_function = [-0.5 * x + 0.5, 0.5 * x + 0.5] + [(legendre_poly[n - 1] - legendre_poly[n - 3]) * ((1 / (2 * (2 * n - 3))) ** 0.5) for n in range(3, max_degree + 2)]
# Calculating the Derivative of Shape Function
shape_prime = [sympy.diff(y, x) for y in shape_function]
# Defining Mapping Function
mapping = []
for i in range(0, num_nod_point - 1):
mapping += [(1 - x) * nod_point[i] / 2 + (1 + x) * nod_point[i + 1] / 2]
if __name__ == "__main__"
q = multiprocessing.Queue()
p1 = multiprocessing.Process(target=da_k, args=(num_element, degree, h, shape_prime, px, mapping))
p2 = multiprocessing.Process(target=da_m, args=(num_element, degree, h, shape_function, cx, mapping))
p3 = multiprocessing.Process(target=da_f, args=(num_element, degree, h, shape_function, fx, mapping))
p1.start()
p2.start()
p3.start()
p1.join()
p2.join()
p3.join()
global_k, total_local_k = q.get()
global_m, total_local_m = q.get()
global_f, total_local_f = q.get()
print(global_k,global_m,global_f)
File "C:\Python\WinPython-64bit-3.5.1.1\python-3.5.1.amd64\lib\multiprocessing\spawn.py", line 137, in _check_not_importing_main
is not going to be frozen to produce an executable.''')
RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
This probably means that you are not using fork to start your
child processes and you have forgotten to use the proper idiom
in the main module:
if __name__ == '__main__':
freeze_support()
...
The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce an executable.
I'm learning multiprocess module recently,and I added the multiprocess module in my code, but the program will run 3 times when I click "run", there must be something wrong of the multiprocess part,cuz the other parts works well before I adding multiprocess module. Does anyone could help me to use multi-process module correctly? Thanks very much!
Update: I checked the multiprocess code, and it works fine, so the problem should be about the queue, thanks for your help.
The RuntimeError is because you are missing a colon at the end of
if __name__ == "__main__"
It should be
if __name__ == "__main__":
With the colon missing, all the code before that line will be run when you execute the code. Also seems you haven't included all your code, can't see you put anything into Queue anywhere.