Can anyone help with float values in python.
I want to access values from CPP.From cpp I am getting value say 20.251.
But in python its displaying as20.25099876 sometng like this.
I want to display value as it is coming frm cpp.
Thanks .
I have tried
i = c_ float
GetVal(Voltage, byref(i))
Print("Value is: " i.value)
Here you go
a = 20.25099876
result = format(a, '.3f')
print result
Decimals and floats are different in the sense that decimals have a base of ten (0-9) whereas float have a base of two (0,1). There are two approaches to rounding (not truncating the floating point, which just cuts the number off at the indicated decimal).
x = 20.25099876
s = format(x, '.2f')
print(s)
The .2 indicates the number of numbers post-float to print
rounding notation can be placed after a colon & inside braces of format strings
x = 20.25099876
'rounded : {:.2f}'.format(x)
One way to print the number without rounding is
num=20.25099876
num = num - (num % 0.0001)
print num
It will print 20.2509
If you want to print the value as it is , like a=20.25099876
Make it string. str(a) and print it.
Use "c_double" instead of "c_float" to get exact values from cpp.
Related
I have a python code that when given a small number between 0 and 1 doesn't print it fully, but 4.43017984825e-7 for example,how do I make the code shows the whole number with all zeroes?
this was my try:
number="4.43017984825e-7"
result=number.find("e")
new=list(number)
last=int(new[-1])
print(last)
del new[13:16]
print(new)
pricee=(''.join(new))
print(pricee)
price=float(pricee)*10**-(last)
print(price)
Note: the number changes everytime, so I want it to be applicable for all numbers.
You can probably accomplish what you want with fixed-point formatting.
>>> x=4.43017984825e-7
>>> print(x)
4.43017984825e-07
>>> print(f"{x:20.18f}")
0.000000443017984825
The 20 in that format tells the full width you want, while the 18 tells the number of decimals.
Now, this is fairly specific to this number, you'll have to pick the right length and number of decimals for your actual application.
Expanding on the suggestion from #MostafaFarzán: you can use log10 to adjust that fixed point formatting to any number:
x = <some float>
significant_digits = 8
decimals=max(0, int(-log10(x) + significant_digits))
print(f"%.{decimals}f" % x)
or, more concisely but harder to read:
print(f"%.{max(0, int(-log10(x) + 8))}f" % x)
import math
a = math.sqrt(25)
print(a)
My output is 5.0, how can I get a 5 (whole number) instead?
You have to check and explicitly convert to integer:
if x == (y := int(x)):
x = y
Or, without the assignment operator:
if x == int(x):
x = int(x)
As of python 3.8, you can use math.isqrt:
math.isqrt(25)
Keep in mind that this will always return an integer, even if the input is not a perfect square.
In a reduced manner, you can use a 1 line if operator to assign an integer value to the result of sqrt if both integer and decimal values are the same:
import math
a = math.sqrt(25)
a = int(a) if int(a)==a else a
print(a)
It depends a little on what exact behavior you want: do you want to just print the number without the decimal, or do you want to round a number to an integer?
For the print statement, Python tries to convert whatever is passed to it to a String in order to print it, and by default it gives floating point numbers decimal places. To stop that, we can use string formatting:
print("{:.0f}".format(a))
What this is doing is making a string (the double quotes "") that contains a special format marker (the curly braces {}). Inside the format marker is the code for the desired behavior (0 decimal places on a floating point number). Then we call the .format method of the string and pass the value (a) we want to be used inside the special format marker.
This looks somewhat arcane and ugly, but is the safest method to print what you want because it does not change 'a' and is easily customizable to other printing behaviors.
For rounding a number and converting it to an int, you can either use int() or round(): both will take in a float and output an integer that will print cleanly (and be an integer for future computation). There is no requirement for the thing being converted to actually be an integer but there is different behavior for the two functions: int returns the value of the first digit of a number, while round returns the rounded value (IE round(1.9) -> 2, int(1.9) -> 1, etc).
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.
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.
I have a list with floats, each number with 3 decimals (eg. 474.259). If I verify the number in the list like this:
if 474.259 in list_sample:
print "something!"
Then the message is shown, but if I take the number from another list and I round it:
number = other_list[10]
number = round(number, 3)
if number == 474.259:
print "the numbers are same!"
if number in list_sample:
print "something!"
The second message is not shown.
Comparing floating point numbers for exact equality usually won't do what you want. This is because floating point numbers in computers have a representation (storage format) which is inherently inaccurate for many real numbers.
I suggest reading about it here: http://floating-point-gui.de/ and doing something like a "fuzzy compare" using an "epsilon" tolerance value to consider the numbers equal so long as they differ by less than x% or whatever.
You could also following an approach, where you compare the values based on an arbitrary precision.
For example, convert all your floats like this:
def internalPrecision(number):
precision = 1000
return int(round(number * precision))
If you do this, both operators == and in should work.
You can use numpy.isclose() instead of Python's in.
import numpy as np
other_list = np.array([474.251001, 123.456])
number = other_list[0]
number = round(number, 3)
if number == 474.251:
print "number == 474.251"
if number in other_list:
print "number in other_list"
if any(np.isclose(number, other_list, rtol=1e-7)):
print 'any(np.isclose(number, other_list, rtol=1e-7))'
Output:
number == 474.251
any(np.isclose(number, other_list, rtol=1e-7))