Random walk code in python [2 dimensions] - python-2.7

Please could you help me by figuring out what is the wrong with my code.
I am trying to write a program that generates random walks in two dimensions and that determines statistics about the position of the walker after 500 steps when the number of walks is 1000, the max step size is 0.9, and the separation between the two positions is 0.001.
import math
import random
import time
print "RANDOM WALKS ANALYSIS IN ONE DIMENSION"
NOFW_ = 1000 #The number of walks
NOFS_= 500 #The number of steps in each walk
MSS_ = 0.9 # The maximum step size[m]
SOFP_ = 0.001 # The separation of positions considered equal[m]
print " Number of walks: %3g"% NOFW_
print " Number of steps in each Walk: %3g"% NOFS_
print " Maximum step size: %3g"% MSS_,"m"
print "Separation of positions considered equal: %3g"% SOFP_,"m"
print
print "Please wait while random walks are generated and analyzed..."
print "Date:" + time.ctime()
print
def initialPosition():
return (0.0, 0.0)
def distance(posA, posB):
"""Calculates the distance between two positions posA and posB"""
distance = math.sqrt((posB[0] - posA[0])**2 + (posB[1] - posA[1])**2)
return distance
def printstats(description, numbers):
minimum_value_ = min(numbers)
numbers.sort()
Tenth_percentile = abs(0.10*len(numbers) + 0.5)
Mean_value_ = (1./float(len(numbers))*sum(numbers))
A = 0
for values in numbers:
B = distance(values, Mean_value_)
B = B**2
A = B + A
Standard_deviation = math.sqrt((1./(len(numbers)-1))*A)
Newposition_ = int(0.90*(len(numbers) + 0.5))
Ninetieth_percentile =numbers[Newposition_]
maximum_value_ = max(numbers)
print "Analysis for"""+ description
print "Minimum value: %9.1f" % minimum_value_
print "10th percentile: %7.1f" % Tenth_percentile
print "Mean value: %12.1f" % Mean_value_
print "Standard deviation: %4.1f" % Standard_deviation
print "90th percentile: %7.1f" % Ninetieth_percentile
print "Maximum value: %9.1f" % maximum_value_
list_1 = [minimum_value_, Tenth_percentile, Mean_value_, Standard_deviation, Ninetieth_percentile,maximum_value_]
return list_1
def takeStep(prevPosition, maxStep):
x = random.random()
y = random.random()
minStep = -maxStep
Z = random.random()*2*math.pi
stepsize_ = random.random()*0.9
Stepx= stepsize_*math.cos(Z)
Stepy= stepsize_*math.sin(Z)
New_positionx = prevPosition[0] + Stepx
New_positiony = prevPosition[1] + Stepy
return (New_positionx, New_positiony)
Step_100 = []
Step_500 = []
count_list = []
for walk in range(NOFW_):
Step1 = []
Position = (0.0,0.0)
count = 0
for step in range(NOFS_):
Next_Step_ = takeStep(Position, MSS_)
for word in Step1:
if distance(Next_Step_, word) <= SOFP_:
count +=1
position = Next_Step_
Step1.append(Next_Step_)
Step_100.append(Step1[-1])
Step_500.append(Step1[-1])
count_list.append(count)
Step_100 = printstats("distance from start at step 100 [m]", Step_100)
Step_500 = printstats("distance from start at step 500 [m]", Step_500)
count_list = printstats("times position revisited", count_list)

Your problem is here
Mean_value_ = (1./float(len(numbers))*sum(numbers))
sum() is supposed to get some numbers but your variable numbers is actually containing some tuples of 2 values
You may want to define your own sum function for tuples of 2 numbers, or to sum the first values and second values separately

Related

Implementation of Karger's Algorithm in Python Taking too Long

Wondering if you can help me understand where the critical flaw may be with my attempt at implementing Karger's algorithm in python. My program appears to take far too long to run and my computer starts to overwork running large sets of vertices. The purpose of the program is to output the minimum cut of the graph.
from random import choice
from statistics import mode
import math
fhand = open("mincuts.txt", "r")
vertices = fhand.readlines()
d = {}
for index,line in enumerate(vertices):
d["{0}".format(index+1)] = line.split()
def randy(graph, x):
y = str(choice(list(graph)))
if x == y:
y = randy(graph, x)
return y
count = 0
def contract(graph):
global count
if len(graph) == 2:
a = list(graph.keys())[0]
b = list(graph.keys())[1]
for i in range(1, len(graph[a])):
if graph[a][i] in graph[b]:
count = count + 1
#print(graph)
return
x = str(choice(list(graph)))
y = randy(graph, x)
#print(x)
#print(y)
graph[x] = graph[x] + graph[y]
graph.pop(y)
#remove self loops
for key in graph:
#method to remove duplicate entries in the arrays of the vertices. Source: www.w3schools.com
graph[key] = list(dict.fromkeys(graph[key]))
contract(graph)
N = len(d)
runs = int(N*N*(math.log(N)))
outcomes = []
for i in range(runs):
e = d.copy()
count = 0
contract(e)
outcomes.append(count)
print(outcomes)
#returns most common minimum cut value
print(mode(outcomes))
Below is a link to the graph I am running in mincuts.txt:
https://github.com/BigSoundCode/Misc-Algorithm-Implementations/blob/main/mincuts.txt

Find maximum and minimum of multivariable function in sympy

I have the following function:
f = x**2 + y**2
I would like to use sympy to find the maximum of and minimum value in the unit square [0,1] in x and [0,1] in y.
The expected outcome would be 0 for point [0,0] and 2 for point [1,1]
Can this be achieved?
I did something clunky, but appears to work [although not fast]:
def findMaxMin(f):
# find stationary points:
stationary_points = sym.solve([f.diff(x), f.diff(y)], [x, y], dict=True)
# Append boundary points
stationary_points.append({x:0, y:0})
stationary_points.append({x:1, y:0})
stationary_points.append({x:1, y:1})
stationary_points.append({x:0, y:1})
# store results after evaluation
results = []
# iteration counter
j = -1
for i in range(len(stationary_points)):
j = j+1
x1 = stationary_points[j].get(x)
y1 = stationary_points[j].get(y)
# If point is in the domain evalute and append it
if (0 <= x1 <= 1) and ( 0 <= y1 <= 1):
tmp = f.subs({x:x1, y:y1})
results.append(tmp)
else:
# else remove the point
stationary_points.pop(j)
j = j-1
# Variables to store info
returnMax = []
returnMin = []
# Get the maximum value
maximum = max(results)
# Get the position of all the maximum values
maxpos = [i for i,j in enumerate(results) if j==maximum]
# Append only unique points
append = False
for item in maxpos:
for i in returnMax:
if (stationary_points[item] in i.values()):
append = True
if (not(append)):
returnMax.append({maximum: stationary_points[item]})
# Get the minimum value
minimum = min(results)
# Get the position of all the minimum values
minpos = [i for i,j in enumerate(results) if j==minimum ]
# Append only unique points
append = False
for item in minpos:
for i in returnMin:
if (stationary_points[item] in i.values()):
append = True
if (not(append)):
returnMin.append({minimum: stationary_points[item]})
return [returnMax, returnMin]

printing output as a table in python terminal and saving output as a .txt with proper headings

I have written a code to find approximated sum of an exponential function, which should run iteration till N-1 terms, then return the iteration no, sum, abs error and relative error for each iteration step.
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import math
N = input ("Please enter an integer at which term you want to turncate your summation")
x = input ("please enter a number for which you want to run the exponential summation e^{x}")
function= math.exp(x)
exp_sum = 0.0
abs_err = 0.0
rel_err = 0.0
for n in range (0, N):
factorial = math.factorial(n)
power = x**n
nth_term = power/factorial
exp_sum = exp_sum + nth_term
abs_err = abs(function - exp_sum)
rel_err = abs(abs_err)/abs(function)
print "The exponential function which has %d-term expansion, returns the approximated sum to be %.16f." % (n, exp_sum)
print "This approximated sum has an absolute error to be %.25f" % abs_err
print "and a relative error to be %.25f" % rel_err
right now, it actually looks silly printing values at each iteration and it only looks good till a few iteration, my plan is to get the output as a table with proper column headings (iteration, sum, abs err, rel err) in the terminal after I execute the .py file.
also I wish to save a .txt file of the output, if anyone has idea how to do that in python, I would very much appreciate the help and thanks.
You might use a pretty_table() function in order to pretty print tabular data, like this:
def pretty_table(rows, column_count, column_spacing=4):
aligned_columns = []
for column in range(column_count):
column_data = list(map(lambda row: row[column], rows))
aligned_columns.append((max(map(len, column_data)) + column_spacing, column_data))
for row in range(len(rows)):
aligned_row = map(lambda x: (x[0], x[1][row]), aligned_columns)
yield ''.join(map(lambda x: x[1] + ' ' * (x[0] - len(x[1])), aligned_row))
This little function, given a list of rows and the number of columns, will yield pretty-formatted table data, line by line. You can even adjust the spacing between columns if you wish.
In your particular code, you may do the following:
# At first, contains just the header columns.
rows = [['Term', 'Exponential sum', 'Absolute error', 'Relative error']]
for n in range (0, N):
factorial = math.factorial(n)
power = x**n
nth_term = power/factorial
exp_sum = exp_sum + nth_term
abs_err = abs(function - exp_sum)
rel_err = abs(abs_err)/abs(function)
rows.append((str(n), str(exp_sum), str(abs_err), str(rel_err)))
for line in pretty_table(rows, 4):
print(line)
For an input of N = 10, X = 5, this code outputs:
Term Exponential sum Absolute error Relative error
0 1.0 147.413159103 0.993262053001
1 6.0 142.413159103 0.959572318005
2 18.5 129.913159103 0.875347980517
3 39.3333333333 109.079825769 0.734974084703
4 65.375 83.0381591026 0.559506714935
5 91.4166666667 56.9964924359 0.384039345167
6 113.118055556 35.295103547 0.237816537027
7 128.619047619 19.7941114835 0.13337167407
8 138.307167659 10.1059914438 0.0680936347218
9 143.68945657 4.72370253291 0.0318280573062
If you want to redirect it into a file, do this instead of the last for loop:
with open('my_file.txt', 'w') as output:
for line in pretty_table(rows, 4):
print >> output, line

How to avoid duplicate printing of random choiced names from list ( Python)

This program prints duplicate names generated from list please help me get rid of it I added a operator fr it but it's not working
#Subscriber Selector
import random
print "Welcome to Subscriber Picker"
sub_list = ["Ali Abbas","Ansar Abbasi","Hasan Abidi","Saadia Afzaal","Iqbal Ahmad","Iftikhar Ahmad","Khaled Ahmed","Ahmed Tamim","Maulana Mahboob Alam","Malik Barkat Ali"]
def add_list():
input_1 = int(raw_input("How many new users do you want to add? "))
for z in range (0,input_1):
sub_list.append(raw_input ("Enter Name" +" "+ str(z+1) + ":"))
return
add_list()
def generator():
input_2=int(raw_input("How many subscribers to generate? "))
print "-----"
index=0
temp_list = []
ran_name = random.randint(0, len(sub_list)-1)
temp_list.append(sub_list[ran_name])
while len(temp_list) < input_2:
ran_name=random.randint(0,len(sub_list)-1)
temp_list.append(sub_list[ran_name])
if(temp_list[index] == temp_list[index+1]):
temp_list.pop(index)
else:
index = index + 1
for x in temp_list:
print x
print"-----"
return
generator()
Here you go:
temp_list = random.sample( sub_list, input_2 )

Python 2.7 for loop confusion

I'm trying to build a table from user input to export via Cheetah to fill a template to use as a report. I'm having trouble separating each iteration of the loop
"for j in range(1, numErrors):" and put table row tags at the beginning and end of each concatenation.
table = ""
cells = ""
row = ""
numMeas = int(raw_input("Enter total number of measurements: "))
numMeas = numMeas + 1 #number of measurements compensated for iteration behavior
for i in range(1, numMeas):
typeMeas = raw_input("Enter type of measurement "+str(i)+": ")
numErrors = int(raw_input("Enter number of error sources: "))
numErrors = numErrors + 1
for j in range(1, numErrors): #builds dataSet from number of errors
inputData = []
inputData.append(typeMeas)
description = raw_input("Enter source of uncertainty "+str(j)+": ")
inputData.append(description)
estUncert = raw_input("Enter estimated uncertainty "+str(j)+": ")
estUncert = float(estUncert)
inputData.append(str(estUncert))
for i in inputData:
cell = "<td>"+str(i)+"</td>"
cells += cell
table = "<tr>"+cells+"</tr>"+"\n"
print table
Current output:
<tr><td>mass</td><td>scale</td><td>1.0</td><td>mass</td><td>human</td><td>2.0</td> <td>temp</td><td>room</td><td>3.0</td><td>temp</td><td>therm</td><td>4.0</td></tr>
Desired output:
<tr><td>mass</td><td>scale</td><td>1.0</td></tr>
<tr><td>mass</td><td>human</td><td>2.0</td></tr>
<tr><td>temp</td><td>room</td><td>3.0</td></tr>
<tr><td>temp</td><td>therm</td><td>4.0</td></tr>
I am guessing it probably needs to look like this:
table = ""
cells = ""
row = ""
numMeas = int(raw_input("Enter total number of measurements: "))
numMeas = numMeas + 1 #number of measurements compensated for iteration behavior
for i in range(1, numMeas):
typeMeas = raw_input("Enter type of measurement "+str(i)+": ")
numErrors = int(raw_input("Enter number of error sources: "))
numErrors = numErrors + 1
inputData = []
for j in range(1, numErrors): #builds dataSet from number of errors
inputData.append(typeMeas)
description = raw_input("Enter source of uncertainty "+str(j)+": ")
inputData.append(description)
estUncert = raw_input("Enter estimated uncertainty "+str(j)+": ")
estUncert = float(estUncert)
inputData.append(str(estUncert))
cells = ''
for i in inputData:
cell = "<td>"+str(i)+"</td>"
cells += cell
table += "<tr>"+cells+"</tr>"+"\n"
print table