Adding a large number with a small number in Python - python

I wrote a program in python which the program has one number with high value (T) and another number with a low value (a). When I add them up, the small number is ignored due to its low value. How can I fix this problem. The part of my program which makes this problem is below.
import random
lambd = 110
T = 56562719533.0
a = random.expovariate(lambd)
T2 = T + a
print T
print T2

You did add the small number but didn't print enough significant figures to see it.
import random
lambd = 110
T = 56562719533.0
a = random.expovariate(lambd)
T2 = T + a
print a
print T
print '%.10f' % T2
# prints: 0.00436707252696
# prints: 56562719533.0
# prints: 56562719533.0043640137
The '%.10f' tells Python to print 10 digits after the decimal point.

Related

Python while loop not reverting to original value when repeating itself

Here is my code:
import math
flag_acc = True
n_tri = 8
r = 1
error = 1
while flag_acc:
accuracy_desired = float(input('To what accuracy would you like pi? (enter number of decimal places desired)'))
acc_des = 1/(10**accuracy_desired)
while error > acc_des:
theta_deg = 360/n_tri
theta_rad = math.radians(theta_deg)
c = math.sqrt(2 - 2*math.cos(theta_rad))
circum = c*n_tri
pie = circum/2
n_tri += 1
error = ((math.pi -pie)/math.pi)
print('Accuracy desired was: %0.3e'%(acc_des))
print('The number of triangles used to meet the desired accuracy was: ',n_tri)
print('Estimate for pi based on number of triangles is: ', pie)
repeat = input('Would you like to repeat with a new precision? (y/n)')
if repeat in ['n', 'N']:
flag_acc = False
My problem is that every time I respond yes to 'repeat' the n_tri value can only increase, even when my new accuracy_desired value has decreased.
I have tried defining n_tri in multiple different places within my code (inside both while loops, and before the while loops as it is now), and in if statements throughout
keep a tag of old accuracy and new accuracy desired and last n_tri
check and increase or decrease the value of n_tri .. from the second time.
import math
flag_acc = True
n_tri = 8
r = 1
error = 1
old_acc=None
while flag_acc:
accuracy_desired = float(input('To what accuracy would you like pi? (enter number of decimal places desired)'))
if not old_acc and accuracy_desired<old_acc:
n_tri=last_tri-2 # n_tri will be one more thane
acc_des = 1/(10**accuracy_desired)
last_tri=n_tri
while error > acc_des:
theta_deg = 360/n_tri
theta_rad = math.radians(theta_deg)
c = math.sqrt(2 - 2*math.cos(theta_rad))
circum = c*n_tri
pie = circum/2
n_tri += 1
error = ((math.pi -pie)/math.pi)
old_acc=accuracy_desired
print('Accuracy desired was: %0.3e'%(acc_des))
print('The number of triangles used to meet the desired accuracy was: ',n_tri)
print('Estimate for pi based on number of triangles is: ', pie)
repeat = input('Would you like to repeat with a new precision? (y/n)')
if repeat in ['n', 'N']:
flag_acc = False

Python User defined number of output decimals

I want to make a small python script to calculate pi to N number of decimal points and then only output that number of decimals. I don't know how to change the print statement to dynamically limit the number of outputted decimals. Here's my code.
#!python
import math
N = input("Enter the number of digits of pi you would like to compute: ")
runs = math.ceil(N/math.log(2))
a_0 = 1.0
b_0 = 1.0/(2.0**(1.0/2.0))
t_0 = 1.0/4.0
p_0 = 1.0
for x in xrange(1,N):
a = (a_0 + b_0)/2
b = (a_0*b_0)**(1.0/2.0)
t = t_0 - p_0*(a_0 - a)**2
p = 2*p_0
pi = ((a_0 + b_0)**2)/(4*t)
print pi
a_0 = a
b_0 = b
t_0 = t
p_0 = p
print 'Pi to %d number of digits is: ' % (N)
print "%0" N "d\n" % pi
I know my last print statement isn't how you implement this feature, but it gives an idea of how you might do it in something kinda like C.
I just want that last print statement to output pi to N number of digits.

I'm trying to make a Python procedure that converts binary numbers to decimal numbers

I'm trying to create a procedure out of the following code in Python:
print "Program for Binary to Decimal Conversion"
dec = 0`enter code here`
bin = 0
factor = 1;
print "Enter Binary Number:",
bin = input()
while(bin > 0):
if( (bin % 10) == 1):
dec += factor
bin /= 10
factor = factor * 2
print "The Decimal Number is: ", dec
It currently runs in the shell asking what the input, I want to make it like a procedure so that it just runs in the python shell without asking anything and the input line would look something like:
procedure(1110101)
You have to declare a procedure in Python as shown [here] (http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/functions.html)
e.g.
def bin2dec(number):
your code
The theory behind binary to decimal conversion is that each digit represents a power of two.
so you could do something like this:
-take in the digits as a string
-iterate through the string multiplying the digit by the power of 2 it represents
like so:
#ex string = 101
def binToDec(string):
binString = str(string).reverse() #reverse to make iteration easier sort of
dec=0;
place=0;
for digit in binString:
dec+= (int(digit))*(2**place)
return dec
A function in Python is defined like so:
def funcname(args):
# indented code is not optional
# these are comments
For instance:
def bin_to_dec(binary):
print "Program for Binary to Decimal Conversion"
dec = 0
factor = 1
while(binary > 0):
if( (binary % 10) == 1):
dec += factor
binary /= 10
factor = factor * 2
print "The Decimal Number is: ", dec
Now you can call that like
bin_to_dec(10010110)
I would advise doing some basic tutorials to learn Python fundamentals. The web has many.
Now check this out:
def bin_to_dec(binary):
return int(binary, 2)
>>> print bin_to_dec('10000000')
128

in python, i have an int and want to substract it from a list

In python: how do I divide an int received by a user from a list while every time it runs in the for loop I need to divide the value I received from the round before in the next round?
This is my code:
a = input('price: ')
b = input('cash paid: ')
coin_bills = [100, 50, 20, 10, 5, 1, 0.5]
if b >= a:
for i in coin_bills:
hef = b - a
print (hef / i), '*', i
else:
print 'pay up!'
Example: a=370 b=500 ---> b-a=130
Now in the loop I will receive (when i=100) 1, and (when i=50) I will receive 2 but I want in the second round (when i=50) to divide 30 (130[=b-a]- 100[=answer of round 1*i]) by 50.
What do I need to change in the code?
Thanks!
You just need to subtract the amount of change you give back at each step from the total amount of change you're returning. It's much easier to see if you change your variable names to something meaningful:
price= int(raw_input('price: ')) # Use int(raw_input()) for safety.
paid= int(raw_input('cash paid: '))
coin_bills=[100,50,20,10,5,1,0.5]
if paid >= price:
change = paid - price
for i in coin_bills:
# Use // to force integer division - not needed in Py2, but good practice
# This means you can't give change in a size less than the smallest coin!
print (change // i),'*',i
change -= (change // i) * i # Subtract what you returned from the total change.
else:
print 'pay up!'
You could also clear up the output a bit by only printing the coins/bills that you actually return. Then the inner loop might look something like this:
for i in coin_bills:
coins_or_bills_returned = change // i
if coins_or_bills_returned: # Only print if there's something worth saying.
print coins_or_bills_returned,'*',i
change -= coins_or_bills_returned * i
OK, I'm assuming that you're trying to calculate change for a transaction using a number of types of bills.
The problem is that you need to keep a running tally of how much change you have left to pay out. I used num_curr_bill to calculate how many of the current bill type you're paying out, and your hef I changed to remaining_change (so it would mean something to me) for the remaining change to pay.
a= input('price: ')
b= input('cash paid: ')
coin_bills=[100,50,20,10,5,1,0.5]
if b>=a:
# Calculate total change to pay out, ONCE (so not in the loop)
remaining_change = b-a
for i in coin_bills:
# Find the number of the current bill to pay out
num_curr_bill = remaining_change/i
# Subtract how much you paid out with the current bill from the remaining change
remaining_change -= num_curr_bill * i
# Print the result for the current bill.
print num_curr_bill,'*',i
else:
print 'pay up!'
So, for a price of 120 and cash paid 175, the output is:
price: 120
cash paid: 175
0 * 100
1 * 50
0 * 20
0 * 10
1 * 5
0 * 1
0.0 * 0.5
One bill for 50 and one for 5 add up to 55, the correct change.
Edit: I'd go more sparingly on the comments in my own code, but I added them here for explanation so that you could more clearly see what my thought process was.
Edit 2: I would consider removing the 0.5 in coin_bills and replacing 1 with 1.0, since any fractional amounts will wind up being fractions of 0.5 anyway.

Benford's law program

I have to write a program that proves Benford's Law for two Data lists. I think I have the code down for the most part but I think there are small errors that I am missing. I am sorry if this is not how the site is supposed to be used but I really need help. Here is my code.
def getData(fileName):
data = []
f = open(fileName,'r')
for line in f:
data.append(line)
f.close()
return data
def getLeadDigitCounts(data):
counts = [0,0,0,0,0,0,0,0,0]
for i in data:
pop = i[1]
digits = pop[0]
int(digits)
counts[digits-1] += 1
return counts
def showResults(counts):
percentage = 0
Sum = 0
num = 0
Total = 0
for i in counts:
Total += i
print"number of data points:",Sum
print
print"digit number percentage"
for i in counts:
Sum += i
percentage = counts[i]/float(Sum)
num = counts[i]
print"5%d 6%d %f"%(i,num,percentage)
def showLeadingDigits(digit,data):
print"Showing data with a leading",digit
for i in data:
if digit == i[i][1]:
print i
def processFile(name):
data = getData(name)
counts = getLeadDigitCounts(data)
showResults(counts)
digit = input('Enter leading digit: ')
showLeadingDigits(digit, data)
def main():
processFile('TexasCountyPop2010.txt')
processFile('MilesofTexasRoad.txt')
main()
Again sorry if this is not how I am supposed to use this site. Also, I can only use programming techniques that the professor has showed us so if you could just give me advice to clean up the code as it is I would really appreciate it.
Also, here are a few lines from my data.
Anderson County 58458
Andrews County 14786
Angelina County 86771
Aransas County 23158
Archer County 9054
Armstrong County 1901
Your error is coming from this line:
int(digits)
This doesn't actually do anything to digits. If you want to convert digits to an integer, you have to re-set the variable:
digits = int(digits)
Also, to properly parse your data, I would do something like this:
for line in data:
place, digits = line.rsplit(None, 1)
digits = int(digits)
counts[digits - 1] += 1
Lets walk though one cycle of your code and I think you'll see what the problem is. I'll be using this file here for data
An, 10, 22
In, 33, 44
Out, 3, 99
Now getData returns:
["An, 10, 22",
"In, 33, 44",
"Out, 3, 99"]
Now take a look the first pass though the loop:
for i in data:
# i = "An, 10, 22"
pop = i[1]
# pop = 'n', the second character of i
digits = pop[0]
# digits = 'n', the first character of pop
int(digits)
# Error here, but you probably wanted digits = int(digits)
counts[digits-1] += 1
Depending on how your data is structured, you need to figure out the logic to extract the digits you expect to get from your file. This logic might do better in the getData funciton, but it mostly depends on the specifics of your data.
Just to share here a different (and maybe more step-by-step) code. It's RUBY.
The thing is, Benford's Law doesn't apply when you have a specific range of random data to extract from. The maximum number of the data set that you are extracting random information from must be undetermined, or infinite.
In other words, say, you used a computer number generator that had a 'set' or specific range from which to extract the numbers, eg. 1-100. You would undoubtedly end up with a random dataset of numbers, yes, but the number 1 would appear as a first digit as often as the number 9 or any other number.
**The interesting** part, actually, happens when you let a computer (or nature) decide randomly, and on each instance, how large you want the random number to potentially be. Then you get a nice, bi-dimensional random dataset, that perfectly attains to Benford's Law. I have generated this RUBY code for you, which will neatly prove that, to our fascination as Mathematicians, Benford's Law works each and every single time!
Take a look at this bit of code I've put together for you!
It's a bit WET, but I'm sure it'll explain.
<-- RUBY CODE BELOW -->
dataset = []
999.times do
random = rand(999)
dataset << rand(random)
end
startwith1 = []
startwith2 = []
startwith3 = []
startwith4 = []
startwith5 = []
startwith6 = []
startwith7 = []
startwith8 = []
startwith9 = []
dataset.each do |element|
case element.to_s.split('')[0].to_i
when 1 then startwith1 << element
when 2 then startwith2 << element
when 3 then startwith3 << element
when 4 then startwith4 << element
when 5 then startwith5 << element
when 6 then startwith6 << element
when 7 then startwith7 << element
when 8 then startwith8 << element
when 9 then startwith9 << element
end
end
a = startwith1.length
b = startwith2.length
c = startwith3.length
d = startwith4.length
e = startwith5.length
f = startwith6.length
g = startwith7.length
h = startwith8.length
i = startwith9.length
sum = a + b + c + d + e + f + g + h + i
p "#{a} times first digit = 1; equating #{(a * 100) / sum}%"
p "#{b} times first digit = 2; equating #{(b * 100) / sum}%"
p "#{c} times first digit = 3; equating #{(c * 100) / sum}%"
p "#{d} times first digit = 4; equating #{(d * 100) / sum}%"
p "#{e} times first digit = 5; equating #{(e * 100) / sum}%"
p "#{f} times first digit = 6; equating #{(f * 100) / sum}%"
p "#{g} times first digit = 7; equating #{(g * 100) / sum}%"
p "#{h} times first digit = 8; equating #{(h * 100) / sum}%"
p "#{i} times first digit = 9; equating #{(i * 100) / sum}%"

Categories

Resources