formatting in python 2.7.12 - python

I am a beginner python programmer and I have learnt the format specifiers in the print statement.so, %3f will mean that the width of the floating point number should be 3.
But,in the following code,output is not like that
import math
print "%3f"%(math.pi)
this code should output 3.1 because we specified the width as 3.
but the output is 3.141593.
My questions:
1.Does specifying only width work for integers and not for floating point numbers?
2.is it must to specify both width and precision while formatting floating point numbers?

Specifying only width works also for floating point numbers. The thing is that the width includes decimal points too. For example, doing:
"%10f" % math.pi # ' 3.141593'
As you can see, the string is 10 characters long. Another thing to take into account here is that by default, python will output 6 decimal points, so doing "%3f" is the same as "%3.6f".
>>> "%3f" % math.pi
'3.141593'
>>> "%3.6f" % math.pi
'3.141593'
>>>
That's why you are not getting your expected output '3.1'. To get that, and knowing the previous concepts you should specify:
"%3.1f" % math.pi
Or just:
"%.1f" % math.pi

I'd just specify the part after the decimal point like this:
>>> print "%.1f"%(math.pi)
3.1

You should also try the arguably better .format method. It offers much more clarity and functionality while formatting. This is will do what you need,
'{:.1f}'.format(math.pi)
You can also specify padding width,if needed, easily like,
'{:6.1f}'.format(math.pi)
You can read up more here https://pyformat.info/

>>> print "%3f" % x
99999.454540
>>> print "%.3f" % x
99999.455
Well the first one in %30.1%f specifies the length of the string/
>>> print "%30.1f" % x
99999.5
Look at this!
>>> print "%.1f" % x
99999.5
See the last one? It has it rounded off. If you don't want to round off then use decimal instead of float.
import math
from decimal import *
getcontext().prec=6
value = Decimal('999.559987').quantize(Decimal('.01'), rounding=ROUND_DOWN)
print str(value)
print '%.2f' % 999.559987
output:
999.55
999.56

%5.3f here is two part. one is integer '5' part and another is floating part '.3'. integer part print the number of space before printing the number. And floating part specify how many number will print after floating point. And there are given so many example previous answer.

Related

How can I check the length of a long float? Python is truncating the length [duplicate]

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.

How to place a number in the middle of string using python?

suppose a float number x=3.1234. I want to print this number in the middle of the string containing space in the left side and right side of x. string length will be variable. Precision of x will be variable. if string length=10 and precision=2 the output will be " 3.14 " Have any function in python that can return this?
This is really nicely documented at https://docs.python.org/3.6/library/string.html#format-specification-mini-language
But since you clearly didn't have time to google for it:
>>> x = 3.1234
>>> length=10
>>> precision=2
>>> f"{x:^{length}.{precision}}"
' 3.1 '
I'm afraid your notion of precision doesn't agree with Python's in the default case. You can fix it by specifying fixed point formatting instead of the default general formatting:
>>> f"{x:^{length}.{precision}f}"
' 3.12 '
This notation is more perspicuous than calling the method str.format(). But in Python 3.5 and earlier you need to do this instead:
>>> "{x:^{length}.{precision}f}".format(x=x, length=length, precision=precision)
But no amount of fiddling with the format is going to make 3.1234 come out as 3.14. I suspect that that was an error in the question, but if you really meant it, then there is no alternative but adjust the value of x before formatting it. Here is one way to do that:
>>> from decimal import *
>>> (Decimal(x) / Decimal ('0.02')).quantize(Decimal('1'), rounding=ROUND_UP) * Decimal('0.02')
Decimal('3.14')
This divides your number into a whole number of chunks of size 0.02, rounding up where necessary, then multiplies by 0.02 again to get the value you want.

Python hide float decimals if it's over 13?

i was doing some calculation and i got something like this:
newInteger = 200
newFloat = 200.0
if newInteger >= newFloat:
print "Something"
when i run my application it didn't print it out but when i test it on python shell, it print Something!!.
so i test this,
>>> number = 200.0000000000001
>>> number
200.0000000000001
but when decimals goes over 13, like so:
>>> number = 200.00000000000001
>>> number
200.0
does python hide the decimal numbers but showing as rounded? knowing the result is quite important when debugging.
is there any way that i can get the full decimals? (i did look up at python documentation, it didn't say anything about printing actual float number.)
It's called floating point round-off error. It has to do with how Python stores floats (in binary), which makes it impossible for floats to have 100% precision.
Here's more info in the docs.
See the decimal module if you need more precision.
If you just want to quickly compare two numbers, there are a couple of tricks for floating point comparison. One of the most popular is comparing the relative error to the machine precision (epsilon):
import sys
def float_equality(x, y, epsilon=sys.float_info.epsilon):
return abs(x - y) <= epsilon * max(abs(x), abs(y))
But this too, is not perfect. For a discussion of the imperfections of this method and some more accurate alternatives, see this article about comparing floats.
Python tends to round numbers:
>>> math.pi
3.141592653589793
>>> "{0:.50f}".format(math.pi)
'3.14159265358979311599796346854418516159057617187500'
>>> "{0:.2f}".format(math.pi)
'3.14'
However, floating point numbers have a specific precision and you can't go beyod it. You can't store arbitrary numbers in floating point:
>>> number = 200.00000000000001
>>> "{:.25f}".format(number)
'200.0000000000000000000000000'
For integers the floating point limit is 2**53:
>>> 2.0**53
9007199254740992.0
>>> 2.0**53 + 1
9007199254740992.0
>>> 2.0**53 + 2
9007199254740994.0
If you want to store arbitrary decimal numbers you should use Decimal module:
>>> from decimal import Decimal
>>> number = Decimal("200.0000000000000000000000000000000000000000001")
>>> number
Decimal('200.0000000000000000000000000000000000000000001')

How to fix floating point decimal to two places even if number is 2.00000

This is what I have:
x = 2.00001
This is what I need:
x = 2.00
I am using:
float("%.2f" % x)
But all I get is:
2
How can I limit the decimal places to two AND make sure there are always two decimal places even if they are zero?
Note: I do not want the final output to be a string.
This works:
'%.2f" % float(x)
Previously I answered with this:
How about this?
def fmt2decimals(x):
s = str(int(x*100))
return s[0:-2] + '.' + s[-2:]
AFAIK you can't get trailing zeros with a format specification like %.2f.
If you can use decimal (https://docs.python.org/2/library/decimal.html) instead of float:
from decimal import Decimal
Decimal('7').quantize(Decimal('.01'))
quantize() specifies where to round to.
https://docs.python.org/2/library/decimal.html#decimal.Decimal.quantize
Have you taken a look at the decimal module? It allows you to do arithmetic while maintaining the proper precision:
>>> from decimal import Decimal
>>> a = Decimal("2.00")
>>> a * 5
Decimal('10.00')
>>> b = Decimal("0.05")
>>> a * b
Decimal('0.1000')
Python also has a builtin "round" function: x = round(2.00001, 2) I believe is the command you would use.
Well, in Python, you can't really round to two zeroes without the result being a string. Python will usually always round to the first zero because of how floating point integers are stored. You can round to two digits if the second digit is not zero, though.
For example, this:
round(2.00001, 2)
#Output: 2.0
vs this:
round(2.00601, 2)
#Output: 2.01

How do I expand a long number (ending in e+##) to show in expanded form?

So, this may be a simple question but I'm having some trouble finding the answer anywhere.
Take for example I have a simple program where I want to divide a by b like so:
def main():
a = 12345678900000000
b = 1.25
answer = (a / b)
print(answer)
main()
This particular example would result in 9.87654312e+15. How do I get Python to ignore simplifying my number and just give me the whole number?
Thanks in advance, sorry if it's really basic, I wouldn't have asked if I could have found it through Google.
You are seeing the default str() conversion for floating point numbers at work. You can pick a different conversion by formatting the number explicitly.
The format() function can do this for you:
>>> n = 9.87654312e+15
>>> format(n, 'f')
'9876543120000000.000000'
See the Format Specification Mini-Language documentation for more options. The 'f' format is but one of several:
Fixed point. Displays the number as a fixed-point number. The default precision is 6.
The default precision resulting in the .000000 six digits after the decimal point; you can alter this by using .<precision>f instead:
>>> format(n, '.1f')
'9876543120000000.0'
but take into account that decimals are rounded to fit the requested precision.
The g format switches between using exponents (e) and f notation, depending on the size of the number, but won't include decimals if the number is whole; you could use a very large precision with 'g' to avoid printing decimals altogether:
>>> format(n, '.53g')
'9876543120000000'
To be explicit, str(n) is the same as format(n, '.12g'), repr(n) is format(n, '.17g'); both can use the exponent format when the exponent is larger than the precision.
just be more specific about the floating point format
>>> print answer
9.87654312e+15
>>> print "%.20f" % answer
9876543120000000.00000000000000000000

Categories

Resources