i have some doubts in using round function correctly ,i want to know how i should use the round function correctly without any problem.
this is how how i coded in python code:
form1:
res = round(float(float(self.inst) - int(self.elt)),1)
also if put:
form2:
res1 = round(2*float(self.pro),1)
--->it doesn't give me any result .
in form1 ,when i put integer values it gives me result but when i put float values , nothing shown .help please i want those lignes of code work normal , with float and integer values.
in form2 nothing shown even i put integer or float values to see if the sentence work.
From round() documentation :
Return number rounded to ndigits precision after the decimal point. If
ndigits is omitted or is None, it returns the nearest integer to its
input.
Rounding an integer will always return the integer you passed to it, no matter what :
round(42, 50)
42
The second parameter is used to ask for a certain number of digit after the dot for floats.
round(1.2)
1
Cause 0 digit after dot is asked.
round(1.2, 1)
1.2
Cause 1 digit after dot is asked.
round(1.2,2)
1.2
2 digits are asked, but the floating number gave in parameter has only one digit.
In your case res1 and res are highly dependent of self.inst self.elt and self.pro so we cannot help you if you are not more specific. I suggest you write your code with one line by operation and check the results at each steps. I think your problem is not coming from the round() function, but the operations inside it.
By the way nobody will figure out what you try to achieve with those variable names.
You dont need the extra float conversion.
I am getting the below result -
a = '14.524'
b = 7.890
res = round((float(a) - int(b)), 1)
print(res)
7.5
res1 = round(2 * float(a), 1)
print(res1)
29
Check for errors in your terminal window.
Related
When calculating the following 2**1000 for example you get the whole value
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
But if you do the same for a float i.e 1.2**1000 it gives
1.5179100891722457e+79
Is there a built-in way to get the whole value of such a calculation (Not in scientific notation)?
The reason for the behavior you're seeing is that the first expression results in an integer since both of its operands are integers, while the second expression is a floating point number because one of the operands is a float. To get the result you want, you can cast the result of the second expression to an int:
>>> int(1.2**1000)
15179100891722457049849556131606991918673074938672571271083893226004713928916992L
You should be able to use format()
a = 1.2**1000
print(format(a, 'f'))
Gives the output 15179100891722457049849556131606991918673074938672571271083893226004713928916992.000000
Try casting to an integer.
int(1.2 ** 1000)
If you want to get decimals though you'll need to do some additional work depending on your goal
You can use this to print it
print("{:.3E}".format(1234567890987654321))
This will output:
1.235E+18
You can also have decimal values. It will format it similarly.
print("{0:.3E}".format(1234567890987654321.98765432))
1.235E+18
If you want to get the full number printed, then you can do the following:
y = 1234567890987654321.98765432
print(f"{y:.22}")
It will output:
1234567890987654400.0
Scratching my head at what seems like the simplest thing ever.
I am working on a polynomial calculator and have been testing it with some values, but python is not adding these two values the way it needs to be.
ans_2 = (-0.423604188255 + 0.42368554704)
print("Ans 2 = : " + str(ans_2))
I am getting this answer:
Ans 2 = : 8.1358785e-05
But I should be getting an answer like this:
=0.00009
Is there something I am doing wrong?
The value 8.1358785e-05 is scientific notation for the value .000081358785. The print function automatically converts to scientific notation for floats under a certain value.
If you want it to print out the value you're looking for, you need to format the string to tell the print function exactly what you're looking for. You can do that like this
In [11]: ans_2 = (-0.423604188255 + 0.42368554704)
In [12]: print("Ans 2 = : {:.7f} ".format(ans_2))
Ans 2 = : 0.0000814
This will format the string to include seven digits after the decimal.
The value 8.1358785e-05 is just another representation of 0.000081358785.
Whenever you see 'e' in your number means that your value was multiplied by 10 to power of anything that goes after 'e'.
In your case it will be:
8.1358785 * 10 ^ (-5) = 0.000081358785
For more info look there
Possibly you are overlooking that there is -ve sign before the first number. That's why you seem to expect the function to return 0.847289735295 (sum of absolute values of operands) instead of the correct answer (their difference according to their sign)
I am trying to write a function to round a floating point number up to n decimal places. The function can take one or two arguments. If there is only one argument the number should be rounded to two decimal places.
This is where I have gotten so far:
def roundno(num,point=2):
import math
x=1*(math.pow(10,-point))
round=0
while (num>x):
while(num>0):
round+=num/10
num=num/10
round*=10
round+=num/10
num=num/10
round*=0.1
return round
I am getting infinity as the output, every time... Where did I go wrong?
I can't see how your algorithm is supposed to round numbers. I guess a similar strategy could work, but you'd need a subtraction in there somewhere...
One way to do this would be to convert the argument to a string, adjust the number of digits after the decimal point, and then convert the string back to a float, but I suspect that your teacher would not like that solution. :)
Here's a simple way to do rounding arithmetically:
def roundno(num, point=2):
scale = 10.0 ** point
return int(num * scale) / scale
data = [123, 12.34, 1.234, 9.8765, 98.76543]
for n in data:
print n, roundno(n), roundno(n, 3)
output
123 123.0 123.0
12.34 12.34 12.34
1.234 1.23 1.234
9.8765 9.87 9.876
98.76543 98.76 98.765
This simply drops unwanted digits, but it's not hard to modify it to round up or off (your question isn't clear on exactly what type of rounding you want).
Note that this function doesn't check the point argument. It really should check that it's a non-negative integer and raise ValueError with an appropriate error message otherwise.
I have some number 0.0000002345E^-60. I want to print the floating point value as it is.
What is the way to do it?
print %f truncates it to 6 digits. Also %n.nf gives fixed numbers. What is the way to print without truncation.
Like this?
>>> print('{:.100f}'.format(0.0000002345E-60))
0.0000000000000000000000000000000000000000000000000000000000000000002344999999999999860343602938602754
As you might notice from the output, it’s not really that clear how you want to do it. Due to the float representation you lose precision and can’t really represent the number precisely. As such it’s not really clear where you want the number to stop displaying.
Also note that the exponential representation is often used to more explicitly show the number of significant digits the number has.
You could also use decimal to not lose the precision due to binary float truncation:
>>> from decimal import Decimal
>>> d = Decimal('0.0000002345E-60')
>>> p = abs(d.as_tuple().exponent)
>>> print(('{:.%df}' % p).format(d))
0.0000000000000000000000000000000000000000000000000000000000000000002345
You can use decimal.Decimal:
>>> from decimal import Decimal
>>> str(Decimal(0.0000002345e-60))
'2.344999999999999860343602938602754401109865640550232148836753621775217856801120686600683401464097113374472942165409862789978024748827516129306833728589548440037314681709534891496105046826414763927459716796875E-67'
This is the actual value of float created by literal 0.0000002345e-60. Its value is a number representable as python float which is closest to actual 0.0000002345 * 10**-60.
float should be generally used for approximate calculations. If you want accurate results you should use something else, like mentioned Decimal.
If I understand, you want to print a float?
The problem is, you cannot print a float.
You can only print a string representation of a float. So, in short, you cannot print a float, that is your answer.
If you accept that you need to print a string representation of a float, and your question is how specify your preferred format for the string representations of your floats, then judging by the comments you have been very unclear in your question.
If you would like to print the string representations of your floats in exponent notation, then the format specification language allows this:
{:g} or {:G}, depending whether or not you want the E in the output to be capitalized). This gets around the default precision for e and E types, which leads to unwanted trailing 0s in the part before the exponent symbol.
Assuming your value is my_float, "{:G}".format(my_float) would print the output the way that the Python interpreter prints it. You could probably just print the number without any formatting and get the same exact result.
If your goal is to print the string representation of the float with its current precision, in non-exponentiated form, User poke describes a good way to do this by casting the float to a Decimal object.
If, for some reason, you do not want to do this, you can do something like is mentioned in this answer. However, you should set 'max_digits' to sys.float_info.max_10_exp, instead of 14 used in the answer. This requires you to import sys at some point prior in the code.
A full example of this would be:
import math
import sys
def precision_and_scale(x):
max_digits = sys.float_info.max_10_exp
int_part = int(abs(x))
magnitude = 1 if int_part == 0 else int(math.log10(int_part)) + 1
if magnitude >= max_digits:
return (magnitude, 0)
frac_part = abs(x) - int_part
multiplier = 10 ** (max_digits - magnitude)
frac_digits = multiplier + int(multiplier * frac_part + 0.5)
while frac_digits % 10 == 0:
frac_digits /= 10
scale = int(math.log10(frac_digits))
return (magnitude + scale, scale)
f = 0.0000002345E^-60
p, s = precision_and_scale(f)
print "{:.{p}f}".format(f, p=p)
But I think the method involving casting to Decimal is probably better, overall.
111111111111111111111111111111111111111111111111111111111111
when i take this as input , it appends an L at the end like this
111111111111111111111111111111111111111111111111111111111111L
thus affecting my calculations on it .. how can i remove it?
import math
t=raw_input()
l1=[]
a=0
while (str(t)!="" and int(t)!= 0):
l=1
k=int(t)
while(k!= 1):
l=l+1
a=(0.5 + 2.5*(k %2))*k + k % 2
k=a
l1.append(l)
t=raw_input()
a=a+1
for i in range(0,int(a)):
print l1[i]
this is my code and it works for every test case except 111111111111111111111111111111111111111111111111111111111111
so i guess something is wrong when python considers such a huge number
It looks like there are two distinct things happening here. First, as the other posters have noted, the L suffix simply indicates that Python has converted the input value to a long integer. The second issue is on this line:
a=(0.5 + 2.5*(k %2))*k + k % 2
This implicitly results in a floating point number for the value of (0.5 + 2.5*(k %2))*k. Since floats only have 53 bits of precision the result is incorrect due to rounding. Try refactoring the line to avoid floating point math, like this:
a=(1 + 5*(k %2))*k//2 + k % 2
It's being input as a Long Integer, which should behave just like any other number in terms of doing calculations. It's only when you display it using repr (or something that invokes repr, like printing a list) that it gets the 'L'.
What exactly is going wrong?
Edit: Thanks for the code. As far as I can see, giving it a long or short number makes no difference, but it's not really clear what it's supposed to do.
As RichieHindle noticed in his answer, it is being represented as a Long Integer. You can read about the different ways that numbers can be represented in Python at the following page.
When I use numbers that large in Python, I see the L at the end of the number as well. It shouldn't affect any of the computations done on the number. For example:
>>> a = 111111111111111111111111111111111111111
>>> a + 1
111111111111111111111111111111111111112L
>>> str(a)
'111111111111111111111111111111111111111'
>>> int(a)
111111111111111111111111111111111111111L
I did that on the python command line. When you output the number, it will have the internal representation for the number, but it shouldn't affect any of your computations. The link I reference above specifies that long integers have unlimited precision. So cool!
Another way to avoid numerical errors in python is to use Decimal type instead of standard float.
Please refer to official docs
Are you sure that L is really part of it? When you print such large numbers, Python will append an L to indicate it's a long integer object.