How to round up/down an int in Python? - python

Let's say I have an arbitrary integer 874,623,123 how do I round it down to 800,000,000 and up to 900,000,000? Another example is 759 round up to 800 or down to 700. The size of the integer is unknown.
Is there a built-in method to do it? If not, what's the best way to work it out? Sorry not a math expert here.
EDIT:
So far I have looked at
Rounding down integers to nearest multiple
Python round up integer to next hundred
Both use a predefined divider

You can use the math module:
import math
n = 874623123
# c contains the same number of digits as n
c = 10 ** int(math.log10(n))
print(math.floor(n/c) * c) # 800000000
print(math.ceil(n/c) * c) # 900000000

Related

How do I increase the amount of decimal points?

This code is used to estimate pi, with the highest objective being time efficiency. With this in mind, I need to increase the amount of decimal places, as currently it is bottlenecked down to 2.
import numpy as np
def main(max_iterations=200):
a, b= np.random.random(max_iterations), np.random.random(max_iterations)
return 4 * (a ** 2 + b ** 2 < 1).sum() / max_iterations
main()
Example of current output:
3.13
One thing I noticed was that upon adding 0s to the max_iterations parameter, the number of decimal places increased along with it. Though, I need a solution within the function, where it wouldn't matter what the value of the parameter was.
Example of what I want as an output:
3.127722772277228
Don't divide an integer by a number with trailing zeros if you want more significance.
With max_iterations=200:
%Run pi_test.py
3.08
With max_iterations=201:
%Run pi_test.py
3.084577114427861

How to get value for 0.5^(5000) in Python3?

Current I want to calculate the value of a=0.5**5000. I knowa is very small value, but I need use a to multiply b, where b = 5000!, a very large value.
But when I calculate value of a=0.5^5000, the result is 0. Does anyone have a good method to solve this problem? Thanks!
I need use a to multiply b, where b = 5000!
I'd just divide 5000! by 25000 or shift it:
from math import factorial
print(factorial(5000) // 2**5000)
print(factorial(5000) >> 5000)
Output:
299375336...(more than 14000 digits)...080261230
Or as #wim points out, fractions.Fraction would be exact:
print(Fraction(factorial(5000), 2**5000))
Output:
958001075...(more than 14000 digits)...568359375/32
Which in decimal notation is:
299375336...(more than 14000 digits)...080261230.46875
So in this case that gives us only five more digits of precision, not much compared to already over 14000. But for example for 5!/25 it would be 3.75 instead of 3, quite a big difference. Then again, this small number (if you're using it as well) might be insignificant in what you're doing overall. Which we don't know because you only told us about this tiny part of your attempt to do whatever it is you're actually after.
Try the decimal module:
>>> from decimal import Decimal
>>> print(Decimal("0.5") ** 5000)
7.079811261048172892385615159E-1506
>>>
Here's an alternative answer using the mpmath library:
import mpmath
a = mpmath.power(0.5, 5000)
b = mpmath.factorial(5000)
c = mpmath.fmul(a, b)
print(a)
print(b)
print(c)
That includes the other calculations that you mentioned.
Output:
7.0798112610481728923856151586941e-1506
4.2285779266055435222010642002336e+16325
2.9937533623001661362907254353912e+14820
Use Decimal :
from decimal import Decimal
if __name__ == '__main__':
a = Decimal(str(0.5)) ** Decimal(str(5000))
print(a)
7.079811261048172892385615159E-1506

Python round calculator

Hey i'm a little noob still but i'm playing around with python and i want to round D to it's nearest decimal, C and H are fixed and D is the rawinput, the whole answer should be rounded but i keep getting decimals,i want this formula :
Q = Square root of [(2 * C * D)/H]
her's my code:*
import math
C=50
H=30
D=int(raw_input())
a=int(round(D))
Q= math.sqrt(2*C*a/H)
print Q
if i enter 100 i get 18.24
i just want it to be 18
i would really appreciate your help, thanks
import math
C = 50
H = 30
a = int(raw_input())
# prints as a float
# Q = round(math.sqrt(2 * C * a / H), 0)
# prints as an int
Q = int(round(math.sqrt(2 * C * a / H), 0))
print Q
Your code appears to be rounding in the wrong place. You're rounding the input a, which was already the integer D. You're not rounding the result of the square root Q, which is a float.
Note that you're code actually has an extra rounding step you may not intend in it. When you divide two integers in Python 2, you'll get another integer, even if the computation should have had a remainder. You get floor division, always rounding towards negative infinity, not to the nearest integer (so e.g. 9/10 is 0). In your code, 2*C*a is an integer, since all values you're multiplying are, and so when you divide by h (another integer), it's going to round the division off. In the case you gave where you entered 100 as the user input, you'll get 333 as the result of the division instead of the more precise 333.3333333333333. This in turn makes your square root calculation give a different value (18.24828759089466 instead of 18.257418583505537).
Anyway, you probably want to use floating point values everywhere except maybe at the end when you round off the value before printing it. You almost certainly don't want to be using integer math by accident as your current code does. One way to do that is to turn one of your constant values into a float, and move the rounding to the end:
C=50.0 # make the calculations use floats, rather than ints
H=30
D=int(raw_input()) # no need for `a` anymore, we're rounding later instead
Q= int(round(math.sqrt(2*C*D/H))) # round after taking the square root, not before
An alternative to using C=50.0 is to put from __future__ import division at the top of your file, which tells Python that you want division between integers to return a float. That's the default behavior in Python 3, and it's much nicer most of the time. If you specifically want "floor" division, you can explicitly ask for it with the // operator. You might also consider actually using Python 3, rather than making do with Python 2's forwards compatibility features.

how to round to higher 10's place in python

I have a bunch of floats and I want to round them up to the next highest multiple of 10.
For example:
10.2 should be 20
10.0 should be 10
16.7 should be 20
94.9 should be 100
I only need it to go from the range 0-100. I tried math.ceil() but that only rounds up to the nearest integer.
Thanks in advance.
from math import ceil
def ceil_to_tens(x):
return int(ceil(x / 10.0)) * 10
Edit: okay, now that I have an undeserved "Nice answer" badge for this answer, I think owe the community with a proper solution using the decimal module that does not suffer from these problems :) Thanks to Jeff for pointing this out. So, a solution using decimal works as follows:
from decimal import Decimal, ROUND_UP
def ceil_to_tens_decimal(x):
return (Decimal(x) / 10).quantize(1, rounding=ROUND_UP) * 10
Of course the above code requires x to be an integer, a string or a Decimal object - floats won't work as that would defeat the whole purpose of using the decimal module.
It's a pity that Decimal.quantize does not work properly with numbers larger than 1, it would have saved the division-multiplication trick.
>>> x = 16.7
>>> int( 10 * math.ceil(x/10.0))
The answers here are fraught with peril. For example 11*1.1 - 2.1 = 10.0, right? But wait:
>>> x = 11*1.1 - 2.1
>>> int(ceil(x / 10.0)) * 10
20
>>> x
10.000000000000002
>>>
You could try this
int(ceil(round(x, 12) / 10.0)) * 10
But choosing the number of decimal places to round to is really difficult as it is hard to predict how floating point noise accumulates. If it is really important to get this right all of the time, then you need to use fixed point arithmetic or Decimal.
If you're looking for another solution that doesn't involve float division, here's one that uses the modulus:
def ceil_to_tens_mod(x):
tmp = int(ceil(x))
mod10 = tmp % 10
return tmp - mod10 + (10 if mod10 else 0)
There's probably some way to simplify it, but there you go.

Division by Zero Errors

I have a problem with this question from my professor. Here is the question:
Write the definition of a function typing_speed , that receives two parameters. The first is the number of words that a person has typed (an int greater than or equal to zero) in a particular time interval. The second is the length of the time interval in seconds (an int greater than zero). The function returns the typing speed of that person in words per minute (a float ).
Here is my code:
def typing_speed(num_words,time_interval):
if(num_words >= 0 and time_interval > 0):
factor = float(60 / time_interval)
print factor
return float(num_words/(factor))
I know that the "factor" is getting assigned 0 because its not being rounded properly or something. I dont know how to handle these decimals properly. Float isnt doing anything apparently.
Any help is appreciated, thankyou.
When you call float on the division result, it's after the fact the division was treated as an integer division (note: this is Python 2, I assume). It doesn't help, what does help is initially specify the division as a floating-point division, for example by saying 60.0 (the float version of 60):
factor = 60.0 / time_interval
Another way would be divide 60 by float(time_interval)
Note this sample interaction:
In [7]: x = 31
In [8]: 60 / x
Out[8]: 1
In [9]: 60.0 / x
Out[9]: 1.935483870967742
Sharth meant to say: from __future__ import python
Example:
>>> from __future__ import division
>>> 4/3
1.3333333333333333
>>>

Categories

Resources