How to floor numbers to whole number in python [duplicate] - python

This question already has answers here:
How to round a number to significant figures in Python
(26 answers)
Closed 2 years ago.
I am wondering how can I floor 1,999,999 to 1,000,000 or 2,000,108 to 2,000,000 in python?
I used math.floor() but it's just for removing decimal part.

Just do it like this:
math.floor(num / 1000000) * 1000000
e.g.:
>>> num=1999999
>>> math.floor(num / 1000000) * 1000000
1000000.0
>>> num=2000108
>>> math.floor(num / 1000000) * 1000000
2000000.0

To round down positive integer to first digit
from math import floor
def r(n):
gr = 10 ** (len(str(n))-1)
return floor(n / gr) * gr
for i in [199_999, 200_100, 2_100, 315]:
print(r(i))
Output
100000
200000
2000
300

def floor_integer(num):
l = str(num)
return int(l[0]) * pow(10, len(l) - 1)
I think that will fits your needs.
print(floor_integer(5))
# 5
print(floor_integer(133))
# 100
print(floor_integer(1543))
# 1000
print(floor_integer(488765))
# 400000
print(floor_integer(1999999))
# 1000000
print(floor_integer(2000108))
# 2000000

Related

How do you stop Python from converting a number to scientific notation? [duplicate]

This question already has answers here:
How to suppress scientific notation when printing float values?
(16 answers)
Closed 10 months ago.
This is my code:
m = int(input(""))
p= 3.00*10*10*10*10*10*10*10*10
c = p*p
E = m * c
print(E)
The answer is 19e+16.
But I don't want the scientific notation: I want the number.
Actually it is not from VSCode, Python prints that way for better readability. You can print the long form with the help of string formatting. When you apply precision it will expand the printed value:
E = 3.00 * 100 * 100 * 100 * 100 * 100 * 100 * 100 * 100
print(E)
print(f"{E:.1f}")
print(f"{E:.10f}")
output:
3e+16
30000000000000000.0
30000000000000000.0000000000
Possible duplicate of:
How to suppress scientific notation when printing float values?
TL;DR
print('{:f}'.format(E))

Multiply a float with a very large integer in Python

In Python, is there any way to multiply a float with a very large integer?
As an example, I tried print (10**100000) * 1.414
and it gave me:
OverflowError: long int too large to convert to float
Note that the values (the float and that large number) can be anything. More importantly, I want the exact value (rounded to nearest integer) of expression.
Please provide any solution.
If you're looking for the exact value, this means you must have access to 1.414 as a string (otherwise, the value stored in memory isn't exact either).
import decimal
float_string = '1.614' # to show that rounding works
exponent = 100000
decimal.getcontext().prec = exponent + 1
c = 10 ** exponent + 1
d = decimal.Decimal(float_string) * c
print d #1614000.....000002
Convert the float to an integer ratio:
value = 1.414
large = 10**100000
a, b = value.as_integer_ratio()
number, residual = divmod(large * a, b)
number += residual*2 >= b
Edit 2:
Ok, I see what you're after:
import mpmath
mpmath.mp.dps = 100005
i = int(mpmath.mpf("1.414") * 10 ** 100000)
print(str(i)[:10]) # 1414000000
print(len(str(i))) # 100001
print(str(i)[-10:]) # 0000000000
print(str(i).count("0")) # 99997
And for #Stefan:
int(mpmath.mpf("1.414") * (10 ** 100000 + 1000))
returns
14140000000000000 ... 000000000001414 # string contains 99993 0s
Since you accept integer approximations, here is a native solution:
def getint(x, y, z):
z_nu, z_de = z.as_integer_ratio()
return ((x**y) * z_nu) // z_de
Usage:
>>> getint(2, 3, 5.)
40
>>> getint(10, 100000, 1.414)
1413999999999999923616655905789230018854141235351562500000000... # truncated

Weird behaviour inverting float [duplicate]

This question already has answers here:
Why does floating-point arithmetic not give exact results when adding decimal fractions?
(31 answers)
Closed 7 years ago.
With Python 3.4.3
int(1 / 1e-3)
1000
int(1 / 1e-4)
10000
int(1 / 1e-5)
99999
int(1 / 1e-6)
1000000
int(1 / 1e-7)
10000000
Bug or Feature? Any particular reason?
floating point numbers aren't exact. Only binary numbers are.
>>> '%.25f' % 1e-5
'0.0000100000000000000008180'
>>> '%.25f' % (1/1e-5)
'99999.9999999999854480847716331'
So 1/1e-5 is less than 100000 and int cuts off the fractal part.
Converting to int, rounding is the answer:
>>> int(round(1/1e-5))
100000

Correctly write a one-liner mathematical expression in Python

I have a problem that asks me to write one line of python code to do the following:
Calculate the total cost of an item whose original price is $10. You have a 30% discount on it and have to pay 5% state tax. The shipping would cost $7.5.
Following is what I came up with:
10 - (10 * 30 / 100) + (10 - (10 * 30 / 100)) * 5 / 100 + 7.5
As you can see, I am calculating 10 less 30% twice in the above code. I could use a variable to hold 10 - (10 * 30 / 100) but as the problem statement says, I need to do it in one line. Is there a better (read pythonic) way to achieve this?
This problem is from Sam's teach yourself Python in 24 hours book, btw (sorry!).
Just use basic math operations:
print ((0.7*100)*1.05)+7.5
#81.0
int/int can lose precision. You need to divide by 100.0 or float(100) instead of just 100 to get the right result. or insert this code from __future__ import division.
In [17]: 10 - (10 * 30 / 100) + (10 - (10 * 30 / 100)) * 5 / 100 + 7.5
Out[17]: 14.5
In [19]: from __future__ import division
In [20]: 10 - (10 * 30 / 100) + (10 - (10 * 30 / 100)) * 5 / 100 + 7.5
Out[20]: 14.85
You can use variables in a one liner, but you can simplify your solution like this.
print 10 * 0.7 * 1.05 + 7.5
EDIT:
As I mentioned in my comment, The code I posted is all you need. Doing anything more complicated than that can't really be useful as more than an intellectual exercise.
For example ...
print map(lambda x: x + 7.5, map(lambda x: x*1.05, map(lambda x: x*.7, [10])))[0]

int object not callable error

I'm trying this example:
p = 10000
n = 12
r = 8
t = int(input("Enter the number of months the money will be compounded "))
a = p (1 + (r/n)) ** n,t
print (a)
.. but the error is:
TypeError: 'int' object is not callable
Is Python seeing p as a function? If so, is there no way I could do it without importing modules?
Thanks!
Change the line to
a = p * (1 + (r/n)) ** (n * t)
Python doesn't interpret variables that are next to each other as being multiplied (nor would it interpret n, t as that.
Assuming you are using python 3..
p = 10000
n = 12
r = 8
t = int(input("Enter the number of months the money will be compounded: "))
a = p * (1 + (r / n)) ** (n * t)
print(a)
Also double check the units for t, is it in months or years? The formula seems to suggest years (if n = 12 is months per year) but you are prompting for months.
If in python 2.x you would need to import division from __future__, or convert r to float first. And you would use raw_input for the prompt.
You are trying to multiply by p, so you should be explicit and use a *:
a = p * ((1 + (float(r)/n)) ** n,t)
Cast to float (thanks David R) to prevent int rounding problems in division.
you need the "*" operator to multiply numbers
dividing int by int does not give a float so cast one to a float multiply of divide by a float (you will see "*1." in some code to do this"
your input line does not match the variables above (i.e. t should be years not months and n is number of times compounded per year ... 12 for monthly and 4 for quarterly etc)
also need to change your 8 to .08 as a percentage
Try:
p * (1 + (r/100.0/n)) ** (n * t)

Categories

Resources