Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hi I have a somewhat strange question. I am converting a list of numbers (which represent physical measurements), where each are reported to some specified accuracy in arbitrary units depending on the study it comes from. Here is an example of what I mean:
[...,105.0,20.0,3.5,4.25,9.78,7.2,7.2]
These are of course of type:
<type 'numpy.float64'>.
If I print out the last number, for instance:
print list[-1]
>>> 7.2
However, if accessed in this way, I get:
7.2000000000000002
I understand that floats are by default 64 bits, so doing a calculation with them (i.e. - converting this list of measurements) returns a converted value which is 64 bits. Here is an example of the converted values:
[105.27878958,20.0281600192,3.47317185649,4.27596751688,9.82706595042,7.27448290596,7.26291009446]
Accessing them either way (using print or not), returns a 64 bit number. But clearly there is something else going on, otherwise the print function wouldn't really know how to display the true measurement. I would like to report the converted values to the same level of accuracy as the original measurements. Is there a way I can do this in python?
You have three problems:
1) How do I determine the number of decimal places in the input?
If your Python code literally says [...,105.0,20.0,3.5,4.25,9.78,7.2,7.2], you're out of luck. You've already lost the information you need.
If, instead, you have the list of numbers as some kind of input string, then you have the info you need. You probably already have code like:
for line in input_file:
data = [float(x) for x in line.split(',')]
You need to record the number of places to the right of the decimal before converting to float, for example:
for line in input_file:
places = [len(x.partition('.')[2]) for x in line.split(',')]
data = [float(x) for x in line.split(',')]
2) How do I store that information?
That's up to you. Sorry, I can't help you with that one without seeing your whole program.
3) How do I format the output to round to that number of decimal places?
Use the % operator or {}-style formatting, like so:
print '%.*f' % (places[i], data[i])
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
I am trying to get details from DB and store in CSV, but when i open the csv I see the rows for Id reflecting as below:
Id
4.98518E+11
How to remove the E+ from csv wihtout using Pandas.
You are looking at the default str() formatting of floating point numbers, where scientific notation is used for sufficiently small or large numbers.
You don't need to convert this, the value itself is a proper float. If you need to display this in a different format, format it explicitly:
>>> print(0.00001357)
1.357e-05
>>> print(format(0.00001357, 'f'))
0.000014
>>> print(format(0.00001357, '.8f'))
0.00001357
Here the f format always uses fixed point notation for the value. The default precision is 6 digits; the .8 instructs the f formatter to show 8 digits instead.
In Python 3, the default string format is essentially the same as format(fpvalue, '.16g'); the g format uses either a scientific or fixed point presentation depending on the exponent of the number. Python 2 used '.12g'.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
The community reviewed whether to reopen this question 3 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I was working with f-strings, and I am fairly new to python. My question is does the f-string formatting cast a variable(an integer) into a string?
number = 10
print(f"{number} is not a string")
Is number cast into a string?
f"..." expressions format values to strings, integrate the result into a larger string and return that result. That's not quite the same as 'casting'*.
number is an expression here, one that happens to produce an integer object. The integer is then formatted to a string, by calling the __format__ method on that object, with the first argument, a string containing a format specifier, left empty:
>>> number = 10
>>> number.__format__('')
'10'
We'll get to the format specifier later.
The original integer object, 10, didn't change here, it remains an integer, and .__format__() just returned a new object, a string:
>>> f"{number} is not a string"
'10 is not a string'
>>> number
10
>>> type(number)
int
There are more options available to influence the output by adding a format specifier to the {...} placeholder, after a :. You can see what exact options you have by reading the Format Specification Mini Language documentation; this documents what the Python standard types might expect as format specifiers.
For example, you could specify that the number should be left-aligned in a string that's at least 5 characters wide, with the specifier <5:
>>> f"Align the number between brackets: [{number:<5}]"
'Align the number between brackets: [10 ]'
The {number:<5} part tells Python to take the output of number.__format__("<5") and use that as the string value to combine with the rest of the string, in between the [ and ] parts.
This still doesn't change what the number variable references, however.
*: In technical terms, casting means changing the type of a variable. This is not something you do in Python because Python variables don't have a type. Python variables are references to objects, and in Python it is those objects that have a type. You can change what a variable references, e.g. number = str(number) would replace the integer with a string object, but that's not casting either.
You can test it yourself quite easily
number = 10
print(f"{number} is not a string")
print(type(number))
# output is integer
If u can't understand f string or other soln dosent make any sense then try this.
This will help you integrate a variable(integer/char) in a string.
a = "blah blah blah {} blah blah ".format(integer_value)
print(a)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I would like to convert birnary to in using own algorithm.
Here is the code:
binary=""
decimal=""
while binary!="exit":
decimal= input(">>")
decimal = decimal
if decimal!="0":
n = len(decimal) -1
n = pow(n, 2)
print(n)
Input:
1010
Bad Output:
9
When I enter binary and check them with calculator they arent true.
I dont have big clue how to make it so sorry for mistakes in code.
Thanks for reply
You need to move the input (where the user enters a binary number) outside the loop that's processing it. Then you have string containing ones (1) and zeros (0) which you can loop through.
Starting at the right-hand end of the string, multiply that number (1 or 0) by 1 (let's call this multiplier the ordinal) and save the result as total.
Multiply the ordinal by 2.
Grab the next number (from the right) from the input string and multiply it by the ordinal, add the result to total.
Keep going, multiplying the ordinal and using that to multiply the next number from the input string, until you run out of "numbers" in the input string.
Print total
First off, I think the line n = pow(n, 2) might be backwards from what you need. If you're converting binary digits, 2 is the base and n will be the power to raise it to, so you'll need n = pow(2, n).
Now, since you want to add up all the digits that are set to 1, you'll also need to add them to a new variable too. If you have more questions about this just ask here, and I'll see how I can help :)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
While learning python, I could not find the difference between the use of str() and " ".
First code
Second code
With str() function you are changing the number type to String but with "" you just pass the String.
str(3.14) # 3.14 is a number and your are converting it into String.
"3.14" is an String value.
Imagine if you had a variable
pi=3.14
then
str(pi)
would give the result 3.14
whereas
"pi"
would give the result pi. The str() function converts something to its string form. Whereas simple quotes will return the word itself.
str() returns a string representation of an object, while quotation marks indicate the value is a string. To see the difference, consider the following:
x = 3.14
print("x") #outputs the character x
print(str(x)) #string representation of the value of object x
In the first print(), the actual character 'x' is output. This has nothing to with the variable x. However, in the second print(), the value of the object x is converted to a string, so '3.14' is output.
There is no difference between the two. The program will run the same. CodeCademy requires that you use the skills (functions and methods) that it teaches you in that step in order to progress to the next one. The python script doesn't do anything differently, but the CodeCademy code analyzer notices that you didn't accomplish the task the way they wanted you too.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am using python to do some text comparison. The text format is like 44=100. Let's say, I have 2 text, 44=100 and 44=3001. I call the string on the left of = is tag, right is value. Now I need to compare the tag and value for them. The tag must be the same, 44 equals 44, but the values don't have to, as long as its format is the same. ie. 100 and 3001 are in the same format(normal digits). But 1.0E+7 in 44=1.0E+7 is different. tThe point is on value comparison. ie. I write a script comp.py, when I run comp.py 2000 30010, I will get output true; while I run comp.py 100000 1.0E+8, output is false. How can I do it? I am thinking about converting the value into an regular expression and comparing it with other.
pseudo code:
rex1 = '100000'.getRegrex(), rex2 = '1.0E+8'.getRegrex(), rex1.compare(rex2)
Is it a feasible way? any advice?
rex1 = '100000'.getRegrex(), rex2 = '1.0E+8'.getRegrex(), rex1.compare(rex2)
Your approach is wrong. It is not only difficult but also illogical to "deduce" a regexp from a given string. What you would do is:
Define your types. With each type you would have a corresponding regexp.
Compare your input text against all your defined types and check which type it is of.
Compare the two types.
Actually, your idea of rex1 = '100000'.getRegrex() could be done
rex1 = re.compile('10000')
But as Thustmaster pointed out, you may want to define the regular expression with more abstraction of the pattern of your data.