I have the following code and result and I would need each number to be rounded to the first decimal but the lowest one ex: 7.166666666666667 to be 7.1 and not 7.2
I have tried with round_down but it still rounds up
for x in range(0, 9):
income_visits=(income_euro[x]/visits[x])
print(income_visits)
7.166666666666667
7.0
7.666666666666667
11.0
0.1111111111111111
11.333333333333334
162.0
55.0
9.0
here's a little function that does it for you:
def round_down(n, decimals=0):
multiplier = 10 ** decimals
return math.floor(n * multiplier) / multiplier
make sure to import the math library.
example usage:
print(round_down(1.7777, 1))
print(round_down(1.7777, 2))
print(round_down(1.7777, 3))
output:
1.7
1.77
1.777
Here is the solution. Try this..
number = YOUR_NUMBER
float(str(int(number)) + '.' + str(number-int(number))[2:3])
>>> number = 7.166666666666667
>>> print( float(str(int(number)) + '.' + str(number-int(number))[2:3]) )
7.1
>>>
>>> number = 7.116666666666667
>>> print( float(str(int(number)) + '.' + str(number-int(number))[2:3]) )
7.1
>>>
>>> number = 7.196666666666667
>>> print( float(str(int(number)) + '.' + str(number-int(number))[2:3]) )
7.1
>>>
>>> number = 7.096666666666667
>>> print( float(str(int(number)) + '.' + str(number-int(number))[2:3]) )
This could also work.
num = 7.166666666667
print(int(num*10)/10)
What this does is it takes the number (i.e. 7.1666...) multiplies it by 10(71.666...) that way when an integer is taken from it, it returns a whole number (71), then it divides again to get just one decimal place (7.1). Hope this helps.
Related
Python 2 how to do this.Print the value of the series x = 1 + 1/2 + 1/3 + 1/4 + … + 1/n for the user’s input of n.
Here you go:
n = int( input() ) # reading user input
x = 0
for i in range(1, n + 1): # adding 1/1 + 1/2 + 1/3 + ... + 1/n
x += 1.0/i
print(x) # => outputs : 2.283333333333333
There may be a Harmonic Series function in Python packages like math or numpy, or some similar way to deal with it, especially if you need high precision at large values of n. Otherwise, you could just do this:
>>> n = 5
>>> print(sum(1.0/i for i in range(1,n+1)))
2.28333333333
Note that the "1.0" is important for Python 2.x so that it knows to deal with floats. Otherwise things get rounded along the way:
>>> print(sum(1/i for i in range(1,n+1)))
1
Hi I have been experimenting for some time to try and total 7 variables at once. I am trying to calculate the 8th number for GTIN 8 codes. I have tried many things and so far I am using float. I Don't know what it does but people say use it. I need to times the 1,3,5,7 number by 3 and 2,4,6 number by 1. Then find the total of all of them added together. I have looked everywhere and I cant find anything. Anything will help. Thanks Ben
code = input ("enter 7 digit code? ")
sum1 = 3 * (code[0] + ',')
sum2 = code[1] + ','
sum3 = 3 * (code[2] + ',')
sum4 = code[3] + ','
sum5 = 3 * (code[4] + ',')
sum6 = code[5] + ','
sum7 = 3 * (code[6] + ',')
checksum_value = sum1 + sum2 + sum3+ sum4 + sum5+ sum6 + sum7
b = str(checksum_value)
print(b)
Quick solution:
x = "1234567"
checksum_value = sum(int(v) * 3 if i in (0,2,4,6) else int(v) for (i, v) in enumerate(x[:7]))
# (1*3) + 2 + (3*3) + 4 + (5*3) + 6 + (7*3)
# ==
# 3 + 2 + 9 + 4 + 15 + 6 + 21
# ==
# sum(int(v) * 3 if i in (0,2,4,6) else int(v) for (i, v) in enumerate(x[:7]))
Explanation:
# Sum the contained items
sum(
# multiply by three if the index is 0,2,4 or 6
int(v) * 3 if i in (0,2,4,6) else int(v)
# grab our index `i` and value `v` from `enumerate()`
for (i, v) in
# Provide a list of (index, value) from the iterable
enumerate(
# use the first 7 elements
x[:7]
)
)
`enter code here`code = input ("enter 7 digit code? ")
sum1 = 3 * (code[0] + ',')
sum2 = code[1] + ','
sum3 = 3 * (code[2] + ',')
sum4 = code[3] + ','
sum5 = 3 * (code[4] + ',')
sum6 = code[5] + ','
sum7 = 3 * (code[6] + ',')
checksum_value = sum1 + sum2 + sum3+ sum4 + sum5+ sum6 + sum7
b = str(checksum_value)
print(b)
GS1 codes come in different lengths, ranging from GTIN-8 (8 digits) to SSCC (2 digit application ID + 18 digits). Here's a simple, general Python formula that works for any length GS1 identifier:
cd = lambda x: -sum(int(v) * [3,1][i%2] for i, v in enumerate(str(x)[::-1])) % 10
Explanation:
Convert input to string, so input can be numeric or string - just a convenience factor.
Reverse the string - simple way to align the 3x/1x pattern with variable-length input.
The weighting factor is selected based on odd and even input character position by calculating i mod 2. The last character in the input string (i=0 after the string has been reversed) gets 3x.
Calculate the negative weighted sum mod 10. Equivalent to the (10 - (sum mod 10)) mod 10 approach you'd get if you follow the GS1 manual calculation outline exactly, but that's ugly.
Test Cases
## GTIN-8
>>> cd(1234567)
0
>>> cd(9505000)
3
## GTIN-12
>>> cd(71941050001)
6
>>> cd('05042833241')
2
## GTIN-13
>>> cd(900223631103)
6
>>> cd(501234567890)
0
## GTIN-14
>>> cd(1038447886180)
4
>>> cd(1001234512345)
7
## SSCC (20 digits incl. application identifier)
>>> cd('0000718908562723189')
6
>>> cd('0037612345000001009')
1
Can Python disable or not used the rounding off a float?
This is my sample
value = 6.30 * 75.73
value:
477.099
I want only to get the value 477.09 without rounding it off.
You can convert to a string and using string split, append just the last 2 digits of the number
num = 477.097
strnum = str(int(num)) + str(num).split(".")[1][:2]
What you want is called truncating, which is notoriously difficult with float values because of the way they are stored.
If you are doing this for the value itself, you can do this;
value = 6.30 * 75.73
value = (( value * 100 ) // 1) * .01
print(value)
This will print
477.09000000000003
which is equivalent to 477.09 for math calculations.
If you are doing this to display the value, then you can convert to a string and just cut off the last digit that you have. Or, if you don't know how many digits there are after the decimal point, you can get the index of the ".", and cut everything that is 2 after that point, as so:
value = 6.30 * 75.73
val_str = str(value)
rounded_str = val_str[:val_str.index('.') + 3]
This will print
477.09
convert value to string(if value an integer then the code will still work, because before the conversion to a string we convert to a float):
value = = 6.30 * 75.73
value_str = str(float(value))
'{:.2f}'.format(float(value_str[:value_str.index('.') + 3]))
Possibly this? (takes about 100 nanoseconds independent of number of digits)
** note, this does not work for negative numbers as written, so it's of limited use.
value = 6.30 * 75.73
print value
print value - value % 0.01
477.097
477.09
does it really truncate?
value = 1./3.
print value - 0.33333333 # see the leftovers
3.333333331578814e-09
print value - value % 0.01
0.33
print (value - value % 0.01) - 0.33 # no leftovers
0.0
(value - value % 0.01) == 0.33
True
You can try this hack with round:
>>> 6.30 * 75.73
>>> 477.099
>>> DIGITS = 2
>>> round(6.30 * 75.73 - 5.0 * 10**(-DIGITS-1), DIGITS)
>>> 477.09
for some reason, my calculation is not coming out correct. All I'm trying to do is find the average of 3 numbers that a user inputs. Here's def that it sits in, if more is needed, just ask.
#===================== Calculates the average of all three ==========================
def calc_average(self): #average calculation
stop_one_mileage = self.__route[0].stop_one_mileage #stop_one_mileage average
stop_two_mileage = self.__route[0].stop_two_mileage #stop_two_mileage
stop_three_mileage = self.__route[0].stop_three_mileage #stop_three_mileage
avg = int(stop_one_mileage) + int(stop_two_mileage) + int(stop_three_mileage)/3 #adds all three and divides by three
return "<div class='results-container'><span class='title'>Average Mileage: </span><span class='results-container'>" + str(avg) + " miles</span></div>" #returns results
The problem is here:
avg = int(stop_one_mileage) + int(stop_two_mileage) + int(stop_three_mileage)/3
Change it to:
avg = (int(stop_one_mileage) + int(stop_two_mileage) + int(stop_three_mileage))/3
Because this is what's happening:
>>> 2 + 2 + 2 / 3
4
>>> (2 + 2 + 2) / 3
2
Perhaps did you forget to use parenthesis?
avg = (int(stop_one_mileage) + int(stop_two_mileage) + int(stop_three_mileage))/3
Otherwise it will divide only the last number by 3 then it will sum the others. Take a look at Python operator precedence documentation.
I have a column formatting issue:
from math import sqrt
n = raw_input("Example Number? ")
n = float(n)
sqaureRootOfN = sqrt(n)
print '-'*50
print ' # of Decimals', '\t', 'New Root', '\t', 'Percent error'
print '-'*50
for a in range(0,10):
preRoot = float(int(sqaureRootOfN * 10**a))
newRoot = preRoot/10**a
percentError = (n - newRoot**2)/n*100
print ' ', a, '\t\t', newRoot, '\t\t', percentError, '%'
It comes out like:
Not in the same column!?!
#Bjorn has the right answer here, using the String.format specification. Python's string formatter has really powerful methods for aligning things properly. Here's an example:
from math import sqrt
n = raw_input("Example Number? ")
n = float(n)
sqaureRootOfN = sqrt(n)
print '-'*75
print ' # of Decimals', ' ' * 8, 'New Root', ' ' * 10, 'Percent error'
print '-'*75
for a in range(0,10):
preRoot = float(int(sqaureRootOfN * 10**a))
newRoot = preRoot/10**a
percentError = (n - newRoot**2)/n*100
print " {: <20}{: <25}{: <18}".format(a, newRoot, str(percentError) + ' %')
Note that instead of tabs I'm using spaces to space things out. This is because tabs are really not what you want to use here, because the rules for how tabs space things are inconsistent (and depend on what your terminal/viewer settings are).
This is what the answer looks like:
---------------------------------------------------------------------------
# of Decimals New Root Percent error
---------------------------------------------------------------------------
0 9.0 18.1818181818 %
1 9.9 1.0 %
2 9.94 0.198383838384 %
3 9.949 0.0175747474747 %
4 9.9498 0.00149490909092 %
5 9.94987 8.7861717162e-05 %
6 9.949874 7.45871112931e-06 %
7 9.9498743 1.4284843602e-06 %
8 9.94987437 2.14314187048e-08 %
9 9.949874371 1.33066711409e-09 %
Using str.format,
import math
n = float(raw_input("Example Number? "))
squareRootOfN = math.sqrt(n)
print('''\
{dashes}
{d:<16}{r:<15}{p:<}
{dashes}'''.format(dashes = '-'*50, d = ' # of Decimals', r = 'New Root', p = 'Percent error'))
for a in range(0,10):
preRoot = float(int(squareRootOfN * 10**a))
newRoot = preRoot/10**a
percentError = (n - newRoot**2)/n
print(' {d:<14}{r:<15}{p:13.9%}'.format(d = a, r = newRoot, p = percentError))
yields
--------------------------------------------------
# of Decimals New Root Percent error
--------------------------------------------------
0 9.0 18.181818182%
1 9.9 1.000000000%
2 9.94 0.198383838%
3 9.949 0.017574747%
4 9.9498 0.001494909%
5 9.94987 0.000087862%
6 9.949874 0.000007459%
7 9.9498743 0.000001428%
8 9.94987437 0.000000021%
9 9.949874371 0.000000001%
A few tricks/niceties:
Instead of three print statements, you can use one print statement on
a multiline string.
The percent symbol in the format {p:13.9%} lets you leave
percentError as a decimal (without multiplication by 100) and it
places the % at the end for you.
This is how tabs work. To get a correct formatting, you should use string.format. For your example, it could look like this:
print "{0:2d} {1:9.8f} {2:f} %".format(a, newRoot, percentError)