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)
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
Why does the large number give me an integer (or at least no decimal points), but the smaller number give me a bunch of decimal points? Is the way I set the precision or declare the variables wrong?
import math
from mpmath import *
mp.prec=1000
x = 5431526412865007456
print mpf((x)/6)
ACTUAL OUTPUT: 905254402144167909.0
WANTED OUTPUT: 905254402144167909.3333333333333333333333(…)
x = 5431526413
print mpf((x)/6.)
OUTPUT: 905254402.16666662693023681640625
Try using mpf(x)/6 or mpf(x)/6.0. The reason your code didn't work is that it did the division using Python's normal rules, then converted it to a arbitrary-precision number, whereas this converts it first so the division is done using arbitrary-precision math.
How it's going?
I need to generate a random number with a large number of decimal to use in advanced calculation.
I've tried to use this code:
round(random.uniform(min_time, max_time), 1)
But it doesn't work for length of decimals above 15.
If I use, for e.g:
round(random.uniform(0, 0.5), 100)
It returns 0.586422176354875, but I need a code that returns a number with 100 decimals.
Can you help me?
Thanks!
100 decimals
The first problem is how to create a number with 1000 decimals at all.
This won't do:
>>> 1.23456789012345678901234567890
1.2345678901234567
Those are floating point numbers which have limitations far from 100 decimals.
Luckily, in Python, there is the decimal built-in module which can help:
>>> from decimal import Decimal
>>> Decimal('1.2345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901')
Decimal('1.2345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901')
Decimal can have any precision you need and it won't introduce floating point errors, but it will be much slower.
random
Now you just have to create a string with 100 decmals and give it to Decimal.
This will create one random digit:
random.choice('0123456789')
This will create 100 random digits and concatenate them:
''.join(random.choice('0123456789') for i in range(100))
Now just create a Decimal:
Decimal('0.' + ''.join(random.choice('0123456789') for i in range(100)))
This creates a number between 0 and 1. Multiply it or divide to get a different range.
I am looking to do some basic math in python. However, I am dealing with numbers such as
0.0000000001 and -0.00000000001
Are there any variables that can hold 10 decimal places with negative and positive numbers?
If not, I could multiply by 100000000000 and make it one, what is the best variable to hold numbers between -100000000000 and 100000000000?
Thanks :)
You probably want the decimal module:
from decimal import Decimal
x = Decimal('0.0000000001')
y = Decimal('-0.00000000001')
I was quite disappointed when decimal.Decimal(math.sqrt(2)) yielded
Decimal('1.4142135623730951454746218587388284504413604736328125')
and the digits after the 15th decimal place turned out wrong. (Despite happily giving you much more than 15 digits!)
How can I get the first m correct digits in the decimal expansion of sqrt(n) in Python?
Use the sqrt method on Decimal
>>> from decimal import *
>>> getcontext().prec = 100 # Change the precision
>>> Decimal(2).sqrt()
Decimal('1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573')
You can try bigfloat. Example from the project page:
from bigfloat import *
sqrt(2, precision(100)) # compute sqrt(2) with 100 bits of precision
IEEE standard double precision floating point numbers only have 16 digits of precision. Any software/hardware that uses IEEE cannot do better:
http://en.wikipedia.org/wiki/IEEE_754-2008
You'd need a special BigDecimal class implementation, with all math functions implemented to use it. Python has such a thing:
https://literateprograms.org/arbitrary-precision_elementary_mathematical_functions__python_.html
How can I get the first m correct digits in the decimal expansion of sqrt(n) in Python?
One way is to calculate integer square root of the number multiplied by required power of 10. For example, to see the first 20 decimal places of sqrt(2), you can do:
>>> from gmpy2 import isqrt
>>> num = 2
>>> prec = 20
>>> isqrt(num * 10**(2*prec)))
mpz(141421356237309504880)
The isqrt function is actually quite easy to implement yourself using the algorithm provided on the Wikipedia page.