How do I round an input variable to a certain number - python-3.5

I am using python 3+ and I want to round a variable up to 500 and if the input is higher than 500 then it rounds up to 1000. Is there a way I could math.ceil() or round() ?
I have done this so far but I'm not sure whether I have come across it in the right way.
import math
x = int(input("how much data did you use this month? "))
math.ceil(x / 500.0) * 500.0
print(x)
I want to round x up to 500 whatever the number is but if it is higher (e.g - 600) I want it to round it to 1000. The last line does not work and only prints what the user inputted.

math.ceil() returns the value that you expect but you haven't assignet it to anything.
Simply assign that value to your variable.
This is the solution:
import math
x = int(input("how much data did you use this month? "))
x = math.ceil(x / 500.0) * 500.0
print(x)

Have you tried:
x = math.ceil(x / 500.0) * 500.0
to update your x variable before printing your x variable?

Related

How to print the fractional part of the number?

It's my first question
So, the problem is python rounding. I have seen it, but I dont really know how to get around it.
For example: i have the number 10.34 - I need to receive just fractional part, so 0.34
I had some ideas how to do that. One of this:
n = float(input())
print(n - int(n))
In case of 10.34 the code give me "0.33999999999999986" instead 0.34.
I have some ideas how to do it with help of strings or another tools, but the task assumes that I need just some basic tools
Use round:
res = n - int(n)
print(round(res, 10))
n = float(input()) n = n - int(n) n = round(n,2)
https://www.w3schools.com/python/ref_func_round.asp
The round() function returns a floating point number that is a rounded version of the specified number, with the specified number of decimals.
round(number, digits)
For your refrence

Trying to end up with two decimal points on a float, but keep getting 0.0

I have a float and would like to limit to just two decimals.
I've tried format(), and round(), and still just get 0, or 0.0
x = 8.972990688205408e-05
print ("x: ", x)
print ("x using round():", round(x))
print ("x using format():"+"{:.2f}".format(x))
output:
x: 8.972990688205408e-05
x using round(): 0
x using format():0.00
I'm expecting 8.98, or 8.97 depending on what method used. What am I missing?
You are using the scientific notation. As glhr pointed out in the comments, you are trying to round 8.972990688205408e-05 = 0.00008972990688205408. This means trying to round as type float will only print the first two 0s after the decimal points, resulting in 0.00. You will have to format via 0:.2e:
x = 8.972990688205408e-05
print("{0:.2e}".format(x))
This prints:
8.97e-05
You asked in one of your comments on how to get only the 8.97.
This is the way to do it:
y = x*1e+05
print("{0:.2f}".format(y))
output:
8.97
In python (and many other programming language), any number suffix with an e with a number, it is power of 10 with the number.
For example
8.9729e05 = 8.9729 x 10^3 = 8972.9
8.9729e-05 = 8.9729 x 10^-3 = 0.000089729
8.9729e0 = 8.9729 x 10^0 = 8.9729
8.972990688205408e-05 8.972990688205408 x 10^-5 = 0.00008972990688205408
8.9729e # invalid syntax
As pointed out by other answer, if you want to print out the exponential round up, you need to use the correct Python string format, you have many choices to choose from. i.e.
e Floating point exponential format (lowercase, precision default to 6 digit)
e Floating point exponential format (uppercase, precision default to 6 digit).
g Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise
G Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise
e.g.
x = 8.972990688205408e-05
print('{:e}'.format(x)) # 8.972991e-05
print('{:E}'.format(x)) # 8.972991E-05
print('{:.2e}'.format(x)) # 8.97e-05
(Update)
OP asked a way to remove the exponent "E" number. Since str.format() or "%" notation just output a string object, break the "e" notation out of the string will do the trick.
'{:.2e}'.format(x).split("e") # ['8.97', '-05']
print('{:.2e}'.format(x).split('e')[0]) # 8.97
If I understand correctly, you only want to round the mantissa/significand? If you want to keep x as a float and output a float, just specify the precision when calling round:
x = round(8.972990688205408e-05,7)
Output:
8.97e-05
However, I recommend converting x with the decimal module first, which "provides support for fast correctly-rounded decimal floating point arithmetic" (see this answer):
from decimal import Decimal
x = Decimal('8.972990688205408e-05').quantize(Decimal('1e-7')) # output: 0.0000897
print('%.2E' % x)
Output:
8.97E-05
Or use the short form of the format method, which gives the same output:
print(f"{x:.2E}")
rount() returns closest multiple of 10 to the power minus ndigits,
so there is no chance you will get 8.98 or 8.97. you can check here also.

how to generate random numbers between closed interval [0,1]?

I need to get soma random values between closed interval [0,1] rather than opened interval. Is there any way this can be done?
Is this ok?
You can use:
random.uniform(0, 1)
Note: When calling N = random.uniform(a, b), the behaviour is always that a <= N <= b but the end-point value b may or may not be included in the range depending on floating-point rounding.
See https://docs.python.org/3/library/random.html?highlight=uniform#random.uniform
First, try: import random (random.randint(0,10**6)*1.0 /10**6)
This will give you full floating point precision.
Otherwise, try:
import decimal
def randfloat():
decimal.getcontext().prec = 10 # 10 decimal points enough?!
return decimal.Decimal(0) + decimal.Decimal(random.uniform(0, 1))
# this should include both boundaries as float gets close enough to 1 to make decimal round
>>> decimal.Decimal(0) + decimal.Decimal(0.99999999999)
Decimal('1.000000000')
while uniform() apparently guarantees the inclusion of the lower boundary

Why does my if function not return the proper value?

I'm quite new at Python programming so forgive me if it seems like a stupid question. This is my code with the given results:
Code:
def Stopping_Voltage(Frequency, Phi):
x = (4.14E-15) * Frequency ##The value of (h/e) multiplied by frequency
y = Phi / (1.602E-19) ##The value of Phi/e
Energy = x * (1.602E-19)
print(Energy)
print(Phi)
print(x)
print(y)
String = 'No electron is emitted'
if Energy > Phi:
Voltage = x - y
return(Voltage)
else:
return(String)
Stopping_Voltage(10, (6.63228E-33))
Result:
6.632280000000001e-33
6.63228e-33
4.1400000000000005e-14
4.14e-14
6.310887241768095e-30
What we're asked to do is if the energy is less than or equal to phi, return the string but when testing it with the given variables, it should return the string but it is still giving me a quantitative result. I initially tried using "else" rather than "elif" but it still gave me the same thing (if that matters). When I printed the value for Energy and Phi, the energy value has a lot of zeroes after the decimal (with 1 following after all the zeroes). How do I fix this to give me the string?
Your code is fine! It does return the string, if Energy is <= Phi. It's just that your Energy in this particular example is really bigger than your Phi :) This is the scientific notation of a number, so e means 10^exponent like 2e-5 is equal to 2*10^-5. You can check it by adding print(Energy > Phi) which will print you either True or False e.g. before the if-else block.

Statistical Analysis Error? python 3 proof read please

The code below generates two random integers within range specified by argv, tests if the integers match and starts again. At the end it prints some stats about the process.
I've noticed though that increasing the value of argv reduces the percentage of tested possibilities exponentially.
This seems counter intuitive to me so my question is, is this an error in the code or are the numbers real and if so then what am I not thinking about?
#!/usr/bin/python3
import sys
import random
x = int(sys.argv[1])
a = random.randint(0,x)
b = random.randint(0,x)
steps = 1
combos = x**2
while a != b:
a = random.randint(0,x)
b = random.randint(0,x)
steps += 1
percent = (steps / combos) * 100
print()
print()
print('[{} ! {}]'.format(a,b), end=' ')
print('equality!'.upper())
print('steps'.upper(), steps)
print('possble combinations = {}'.format(combos))
print('explored {}% possibilitys'.format(percent))
Thanks
EDIT
For example:
./runscrypt.py 100000
will returm me something like:
[65697 ! 65697] EQUALITY!
STEPS 115867
possble combinations = 10000000000
explored 0.00115867% possibilitys
"explored 0.00115867% possibilitys" <-- This number is too low?
This experiment is really a geometric distribution.
Ie.
Let Y be the random variable of the number of iterations before a match is seen. Then Y is geometrically distributed with parameter 1/x (the probability of generating two matching integers).
The expected value, E[Y] = 1/p where p is the mentioned probability (the proof of this can be found in the link above). So in your case the expected number of iterations is 1/(1/x) = x.
The number of combinations is x^2.
So the expected percentage of explored possibilities is really x/(x^2) = 1/x.
As x approaches infinity, this number approaches 0.
In the case of x=100000, the expected percentage of explored possibilities = 1/100000 = 0.001% which is very close to your numerical result.

Resources