This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 3 years ago.
I am trying to work on a random number generator which produces a random number which is to 2dp regardless of whether it needs to be. eg. 2.10 is 2.10 not 2.1, 3 = 3.00
import random
temp_var_4_int = random.randint(2,5) + round(random.random(),2)
print (temp_var_4_int)
It should randomize a number between 2 and 5 and then add a decimal to it which is rounded to 2 decimal places but I keep getting answers such as:
1.2700000000000002 instead of 1.27
I'm not sure why it's throwing this anomaly at me.
assuming you want your numbers in [0, 10] you could just do this:
from random import uniform
r = round(uniform(0, 10), 2)
print(f"{r:3.2f}")
if r = 2.1 the format string will represent it as "2.10"; but for all mathematical purposes the trailing zero has no effect.
import random
print("Printing random float number with two decimal places is ",
round(random.random(), 2))
print("Random float number between 2.5 and 22.5 with two decimal places is ",
round(random.uniform(2.5,22.5), 2))
You can format the float with two digits like:
import random
temp_var_4_int = random.randint(2,5) + round(random.random(),2)
temp_var_4_int = '%.2f' % (temp_var_4_int)
print(temp_var_4_int)
According to this Q&A
(0.1+.02)
will return
0.12000000000000001
and
'%.2f' % (0.1+.02)
will return
'0.12'
Try it if you please and let me know, is another example of the same issue
Try to use string formatting:
from random import randint, random
temp_var_4_int = round(randint(2,5) + random(), 2)
print(temp_var_4_int)
print(f"{temp_var_4_int:.2f}")
That would output something like:
2.1
2.10
Please note that f-strings works on Python 3.6+
Related
i have a problem in python3
my variable is
i = 31.807
I would transform in this:
i = 31.80
with two numbers after the decimal point and without round even show 0 in end.
Question: how do I round a float in Python to the desired decimal digit?
You can use numpy.round and supply the value to round and the number of significant digits, i.e.
import numpy as np
i = np.round(31.807, 2)
print(i)
the output is going to be 31.81, which differs from you example.
Question: how do I ceil/floor to the desired decimal digit?
Unfortunately numpy.ceil and numpy.floor do not allow for that, so you need to be a bit more crafy:
import numpy as np
i = np.floor(31.807*100)/100
print(i)
the output is now 31.8.
Question: how do I print a number in a specific format?
Here there is no single write way to go, one possibility is:
print("{:.2f}".format(31.8))
Output: 31.80.
I think the solution from this question here: stackoverflow.com/a/37697840/5273907 would solve your problem i.e.:
import math
def truncate(number, digits) -> float:
stepper = 10.0 ** digits
return math.trunc(stepper * number) / stepper
When I test it locally with your example I get:
>>> truncate(31.807, 2)
31.8
I tried to find this question answered, but I haven't found anything related.
I have a variable that can be in a format like 50000.45 or in a format like 0.01.
I need to write this variable in a label that is 4 digits wide.
What is the best way to fit the label showing only the most significant digits?
To better explain, I would like to have for example:
for 50000.45: 50000
for 4786.847: 4786
for 354.5342: 354.5
for 11.43566: 11.43
and for 0.014556: 0.0145
Possibly without having to do:
if ... < variable < ...:
round(variable,xx)
for all cases.
In order to convert a number into a set number of digits, you can convert the number into only decimals (aka 0 <= n <= 1), then remove the last characters. You can do it like that:
from math import log10
number = 123.456789
n_digits = 4
log = int(log10(number) + 1)
number /= 10**log # convert the number into only decimals
number = int(number*10**n_digits)/10**n_digits # keep the n first digits
number *= 10**log # multiply the number back
Or a more compact form:
from math import log10
number = 123.456789
n_digits= 4
log = int(log10(number) + 1) - n_digits
number = int(number/10**log)*10**log
[Edit] You should use Python round() function in a simpler way:
number = round(number, n_digits-int(log10(number))-1)
This question already has answers here:
How to print float to n decimal places including trailing 0s?
(5 answers)
Closed 2 years ago.
It's my first week trying to learn how to code.
Rods is input from user so it can be whatever
miles = round(Rods * 0.003125, 20)
print("Distance in Miles = ", miles)
I need this line of code to print 20 decimals. I thought by adding comma 20 it would do so. I then tried looking re-writing it to format{miles: "20.f"}. (Don't remember exactly how the code went)
Any guidance would be appreciated.
Try this snippet:
miles = Rods * 0.003125
print("Distance in Miles = {:.20f}".format(miles))
This code does the calculation first and formats the answer such that it is displayed in 20 decimal places. For displaying only 10 decimal places change to .10f, for 2 decimal places change to .2f and so on.
When calling round() method on floats, the unnecessary leading decimal zeros are not counted, since the number is the same.
You can convert the number to string, use .split(".") on it to separate the decimal and whole number
example: "3.85".split(".") will return a list whose elements are ["3", "85"] digits = str(num).split(".")
Lets take the second element, decimals decimals = digits[1]
Then you take the length of second element that is decimals and subtract it from 20. This will be the amount of zeros to add. newDecimals = decimals + (20 - len(decimals)) * "0"
Now, use the list from before to form a new number
final = digits[0] + "." + newDecimals
Keep in mind that converting it back to a float will remove those zeros.
Try following source code :
miles = Rods * 0.003125
miles_formatted_float = "{:.20f}".format(miles)
print("Distance in Miles = "+miles_formatted_float)
This question already has answers here:
How to generate a random number with a specific amount of digits?
(10 answers)
Closed 2 years ago.
I'm working on something in python that involves generating a random number that must be 12 digits long, how would I do this?
For example, every time the program is run, it would generate numbers such as 424476789811, etc.
welcome to the SO-community!
How about using random.randint between 10^12 and 10^13 - 1?
import random
print(random.randint(10**12, 10**13 - 1))
# randint is inclusive on both sides, so we need the - 1
# or
print(random.randrange(10**12, 10**13))
# randrange does not include the stop integer
Try using random.randint:
import random
print(random.randint(100000000000, 999999999999))
Output:
785657835683
This gets a random number between 100000000000 and 999999999999.
You can use the following code to get random integer having 12 digits long length and you can its range. Hope it will works for you.Peace!
import random
print(random.randint(1**12, 10**12))
#returns a number between 1 and 9, you can change the range of number by changing 1 and 10.
Well, there are several ways to accomplish this but it all depends on how you want your numbers to be generated. Python's numpy library has a module random which you can use to generate a random number between 0 and 1 (1 not included) with equal probability. i.e. samples of the uniform distribution: numpy.random.rand()
One way to do it would be to take that number you generate and map it from a domain of 0-1 to a domain of 10**11 to 10**12. Keep in mind that although the latter is a 13 digit number the upper bound is not included!
The linear mapping would thus be the line going through the points (0, 1e11) and (1, 1e12). Can you come up with the equation of that line?
Some things to keep in mind:
The data type in this case is of paramount importance: using float32 is not enough for the precision required and so your datatype should be numpy.float64.
Your numbers will be in that range but won't be rounded, so you should use floor to round them (and exclude the top).
How do I get a random decimal.Decimal instance? It appears that the random module only returns floats which are a pita to convert to Decimals.
What's "a random decimal"? Decimals have arbitrary precision, so generating a number with as much randomness as you can hold in a Decimal would take the entire memory of your machine to store.
You have to know how many decimal digits of precision you want in your random number, at which point it's easy to just grab an random integer and divide it. For example if you want two digits above the point and two digits in the fraction (see randrange here):
decimal.Decimal(random.randrange(10000))/100
From the standard library reference :
To create a Decimal from a float, first convert it to a string. This serves as an explicit reminder of the details of the conversion (including representation error).
>>> import random, decimal
>>> decimal.Decimal(str(random.random()))
Decimal('0.467474014342')
Is this what you mean? It doesn't seem like a pita to me. You can scale it into whatever range and precision you want.
If you know how many digits you want after and before the comma, you can use:
>>> import decimal
>>> import random
>>> def gen_random_decimal(i,d):
... return decimal.Decimal('%d.%d' % (random.randint(0,i),random.randint(0,d)))
...
>>> gen_random_decimal(9999,999999) #4 digits before, 6 after
Decimal('4262.786648')
>>> gen_random_decimal(9999,999999)
Decimal('8623.79391')
>>> gen_random_decimal(9999,999999)
Decimal('7706.492775')
>>> gen_random_decimal(99999999999,999999999999) #11 digits before, 12 after
Decimal('35018421976.794013996282')
>>>
The random module has more to offer than "only returning floats", but anyway:
from random import random
from decimal import Decimal
randdecimal = lambda: Decimal("%f" % random.random())
Or did I miss something obvious in your question ?
decimal.Decimal(random.random() * MAX_VAL).quantize(decimal.Decimal('.01'))
Yet another way to make a random decimal.
import random
round(random.randint(1, 1000) * random.random(), 2)
On this example,
random.randint() generates random integer in specified range (inclusively),
random.random() generates random floating point number in the range (0.0, 1.0)
Finally, round() function will round the multiplication result of the abovementioned values multiplication (something long like 254.71921934351644) to the specified number after the decimal point (in our case we'd get 254.71)
import random
y = eval(input("Enter the value of y for the range of random number : "))
x = round(y*random.random(),2) #only for 2 round off
print(x)