# How Python calculate number? [duplicate]

Possible Duplicate:

python - decimal place issues with floats

In [4]: 52+121.2

Out[4]: 173.19999999999999

Asked by:

**Aston478**| Posted: 06-12-2021

# Answer 1

Short answer: Python uses binary arithmetic for floating-point numbers, not decimal arithmetic. Decimal fractions are not exactly representable in binary.

Long answer: What Every Computer Scientist Should Know About Floating-Point Arithmetic

Answered by:**Connie529**| Posted: 07-01-2022

# Answer 2

If you're familiar with the idea that the number "thirteen point two" is written in base ten as "13.2" because it's "10^1 * 1 + 10^0 * 3 + 10^-1 * 2" then try to do the same thing with a base of 2 instead of 10 for the number 173.2.

Here's the whole part: (1 * 2^7) + (0 * 2^6) + (1 * 2^5) + (0 * 2^4) + (1 * 2^3) + (1 * 2^2) + (0 * 2^1) + (0 * 2^0)

Now here's the start fractional part: (0 * 2^-1) + (0 * 2^-2) + (1 * 2^-3)

That's .125, which isn't yet 2/10ths so we need more additions that are of the form (1 * 2^-n), we can carry this out a bit further with (1 * 2^-4) + (1 * 2^-7), which gets us a bit closer ... to 0.1953125, but no matter how long we do this, we'll never get to ".2" because ".2" is not representable as a addition of sums of numbers of the form (1 * 2^-n).

Also see .9999… = 1.0 (http://en.wikipedia.org/wiki/0.999...)

Answered by:**Miranda335**| Posted: 07-01-2022

# Answer 3

Try this:

```
>>> from decimal import Decimal
>>> Decimal("52") + Decimal("121.2")
Decimal("173.2")
```

Answered by: **Joyce651**| Posted: 07-01-2022

# Answer 4

The other answers, pointing to good floating-point resources, are where to start. If you understand floating point roundoff errors, however, and just want your numbers to look prettier and not include a dozen extra digits for that extra last bit of precision, try using str() to print the number rather than repr():

```
>>> 52+121.2
173.19999999999999
>>> str(52+121.2)
'173.2'
```

Answered by: **Agata698**| Posted: 07-01-2022

# Similar questions

python - How to calculate a date back from another date with a given number of work days

I need to calculate date (year, month, day) which is (for example) 18 working days back from another date. It would be enough to eliminate just weekends.
Example: I've got a date 2009-08-21 and a number of 18 workdays as a parameter, and correct answer should be 2009-07-27.
thanks for any help

Python How to calculate number of days between 2 dates?

This question already has answers here:

python - How to calculate the number of times a word is in a text

I'm new in python and i don't know how to solve this: Write a function that calculates the number of times a word appears in a text. This is my code so far but i'm stuck. I think i need to find a way to split the text in words but it's in a list so i can't do it in this way.
def searcher(file):
f = open(file,"r")
word = raw_input("Write your word: ")
text = f.readlines()
text1 = text.split()...

python - how to calculate the number of days in leap year

Write a program that prompts the user to input a month and a year and then output a message to
state how many days are in the given month (note: you will need to consider leap years if the user
enters February for the month)
i used in the first int and input to enter a month and year
if (year/400 == 0) and (year/100 != 0) or (year/4 == 0):

python - How to calculate the number of days between two given dates

import csv
f = csv.reader(open('lmt.csv', 'r')) # open input file for reading
Date, Open, Hihh, mLow, Close, Volume = zip(*f) # split it into separate columns
Now I want to pick two dates out of the Date column and calculate the number of days between them.
Sadly, because they are retrieved from a .csv file, they are in "'\xef\xbb\xbfDate'" format.
So when I attem...

python - Calculate total number of values per day with pandas

I have the following data frame
UNIT C/A DATETIME TOTAL COUNTs
R248 HOO7 2018-03-03 03:00:00 139.0
2018-03-03 07:00:00 927.0
2018-03-04 11:00:00 1946.0
2018-03-05 07:00:00 1330.0
2018-03-05 11:00:00 2358.0
I want to calculate the sum of 'TOTAL COUN...

python - How can I calculate number of days between two dates?

This question already has answers here:

python - How to find the max number we can't calculate by given array?

I have given a set of 4 numbers which I am able use at unlimited amouts. Is there a way to find the highest number that I can not calculate using that set?
I wonder if there is any mathematical formulas to calculate this kind of problems. I also have some basic python knowledge, so I am also curious about any approach using it.
I actually thougt a weird work around with my limited coding knowledge since i ...

python - Calculate count of number of flips per year

I am trying to calculate the count of the number of flips by year but I am having issues at a specific step.
I've created a function to identify flips. (A property was flipped if it was sold within a year of a previous transaction)
I've also calculated the flips and its year for each transaction for each property (columns YearAndFlip?).
Each row represents a property. Each row (property) has one or...

python - how to calculate number of tokens in a file nlp

from urllib import request
from redditscore.tokenizer import CrazyTokenizer
tokenizer = CrazyTokenizer()
url = "http://www.site.uottawa.ca/~diana/csi5386/A1_2020/microblog2011.txt"
with open('your_file.txt', 'a',encoding='utf-8', errors='replace') as f:
for line in request.urlopen(url):
tokens = tokenizer.tokenize(line.decode('utf-8'))
print(tokens)
for item in tokens:
f.writ...

python - Calculate Number of Tweets per Day

I'm trying to write a function which calculates the number of tweets that were posted per day.
Function Specifications:
It should take a pandas dataframe as input. It should return a new dataframe, grouped by day, with the number of tweets for that day. The index of the new dataframe should be named Date, and the column of the new dataframe should be 'Tweets', corresponding to the date and number of tweets...

python - how to calculate days, then a certain number of hours in the days?

I am trying to calculate how many hours I could work If I work four hours a day from today until August 31. So I used an old file, and tried to modify it (silly me) It works, sort of, but I get days, then days worked, but I want hours worked. Here is the code, as bad as it is :) I realize I will need to do something entirely different, but I had a go with some code that I wrote to see how many days until my birthday,...

python - How can I calculate whether one number is a power of another number?

How do I make the is_power_of function return whether the number is a power of the given base? base is assumed to be a positive number.
def is_power_of(number, base):
# Base case: when number is smaller than base.
if number < base:
# If number is equal to 1, it's a power (base**0).
return __
# Recursive case: keep dividing number by base.
return is_power_of(__, ___)
print(is...

python - Calculate number of items in one list are in another

Let's say I have two very large lists (e.g. 10 million rows) with some values or strings. I would like to figure out how many items from list1 are in list2.
As such this can be done by:
true_count = 0
false_count = 0
for i, x in enumerate(list1):
print(i)
if x in list2:
true_count += 1
else:
false_count += 1
print(true_count)
print(false_count)

python - To calculate the number of days between two specified days in Django?

I'm a student studying Django. I want to calculate the number of days between the two specified dates. Currently, View has specified two variables and attempted a subtraction operation, but the following error is being output:
Could not parse the remainder: ' - today' from 'product.due_date|date:"Ymd" - today'
How should I solve this problem? I would appre...

python - How to calculate number of dates within a year of a date in pandas

I have the following dataframe and I need to calculate the amount of ER visit Dates with a score of 1 that are one year after the PheneDate for that pheneDate for a given subject. So basically phenevisit 003v1 has 2 dates within a year of 11/23/05 with a score of 1, which are 5/5/06 and 8/5/06, so its score will be 2 and so on for the other phenevisits.
PheneVisit PheneDate Score ER Date SubjectID
...

python - Calculate total number of unique rows and save the value in a new column

How do I get from that to this:
I know I can count using len() by putting condition inside but actual da...

python - How to calculate the number of days since a given event in each group

Below is a sample data frame:
df = pd.DataFrame({'StudentName': ['Anil','Ramu','Ramu','Anil','Peter','Peter','Anil','Ramu','Peter','Anil'],
'ExamDate': ['2021-01-10','2021-01-20','2021-02-22','2021-03-30','2021-01-04','2021-06-06','2021-04-30','2021-07-30','2021-07-08','2021-09-07'],
'Result': ['Fail','Pass','Fail','Pass','Pass','Pass...

python - How do I specify certain date as the first week and calculate the week number in pandas?

how to convert time to week number
year_start = '2019-05-21'
year_end = '2020-02-22'
How do I get the week number based on the date that I set as first week?
For example 2019-05-21 should be Week 1 instead of 2019-01-01

python - open cv to calculate number of bends in PCB layout trace

How can i use openCV to calculate number of serpentine bends in pcb layout diagram as shown. Here the required output i.e. number of bends is 9. I'm using this script as reference but couldn't find correct output

How to calculate a mod b in Python?

Is there a modulo function in the Python math library?
Isn't 15 % 4, 3? But 15 mod 4 is 1, right?

python - How to calculate a date back from another date with a given number of work days

I need to calculate date (year, month, day) which is (for example) 18 working days back from another date. It would be enough to eliminate just weekends.
Example: I've got a date 2009-08-21 and a number of 18 workdays as a parameter, and correct answer should be 2009-07-27.
thanks for any help

python - Calculate time between time-1 to time-2?

enter time-1 // eg 01:12
enter time-2 // eg 18:59
calculate: time-1 to time-2 / 12
// i.e time between 01:12 to 18:59 divided by 12
How can it be done in Python. I'm a beginner so I really have no clue where to start.
Edited to add: I don't want a timer. Both time-1 and time-2 are entered by the user manually.
Thanks in advance for your help.

python - Calculate Matrix Rank using scipy

I'd like to calculate the mathematical rank of a matrix using scipy. The most obvious function numpy.rank calculates the dimension of an array (ie. scalars have dimension 0, vectors 1, matrices 2, etc...). I am aware that the numpy.linalg.lstsq module has this capability, but I was wondering if such a fundamental...

python - How do you calculate the area of a series of random points?

So I'm working on a piece of code to take positional data for a RC Plane Crop Duster and compute the total surface area transversed (without double counting any area). I cannot figure out how to calculate the area for a given period of operation.
Given the following Table Calculate the area the points cover.
x,y
1,2
1,5
4,3
6,6
3,4
3,1
Any Ideas? I've browsed Greens Theorem and I'...

Python CSV - Need to Group and Calculate values based on one key

I have a simple 3 column csv file that i need to use python to group each row based on one key, then average the values for another key and return them. File is standard csv format, set up as so;
ID, ZIPCODE, RATE
1, 19003, 27.50
2, 19003, 31.33
3, 19083, 41.4
4, 19083, 17.9
5, 19102, 21.40
So basically what I need to do is calculate the average rate col[2] for each unique zipcode col[1] i...

EOL stops python on Calculate Field

Would anyone be able to help me modify these scripts to ignore the error and continue running ? I just need to figure out how to make the script skip over these errors and finish the rest of the lines.
Here is the full Python script:
# Import system modules
import sys, string, os, arcgisscripting
# Create the geoprocessor object
gp = arcgisscripting.create(9.3)
gp.OverWriteOutput = True
# Set the...

python calculate mouse speed

i am using the following method in python to get the X,Y corordinates at any given this
data = display.Display().screen().root.query_pointer()._data
x = data["root_x"]
y = data["root_y"]
z = time.time()
I want to calculate the mouse speed over a given time, is there any way i can calculate and show mouse speed in miles per hour???
krisdigitx
i now managed to fix th...

python - How to calculate slope in numpy

If I have an array of 50 elements, how would I calculate a 3 period slope and a 5 period slope?
The docs dont add much.....
>>> from scipy import stats
>>> import numpy as np
>>> x = np.random.random(10)
>>> y = np.random.random(10)
>>> slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
Would this work?
def slo...

python - How to calculate next Friday?

How can I calculate the date of the next Friday?

python - What's the best way to calculate a 3D (or n-D) centroid?

As part of a project at work I have to calculate the centroid of a set of points in 3D space. Right now I'm doing it in a way that seems simple but naive -- by taking the average of each set of points, as in:
centroid = average(x), average(y), average(z)
where x, y and z are arrays of floating-point numbers. I seem to recall that there is a way to get...

python - Calculate score in a pyramid score system

I am trying to calculate gamescores for a bunch over users and I haven't really got it yet. It is a pyramid game where you can invite people, and the people you invite is placed beneth you in the relations tree.
So if i invite X and X invites Y i get kickback from both of them. Let's say 10%^steps...
So from X i get 10% of his score and 1% from Y, and X get 10% from Y.
So to calculate this i was thi...

How to calculate a mod b in Python?

Is there a modulo function in the Python math library?
Isn't 15 % 4, 3? But 15 mod 4 is 1, right?

To calculate the sum of numbers in a list by Python

My data
466.67
465.56
464.44
463.33
462.22
461.11
460.00
458.89
...
I run in Python
sum(/tmp/1,0)
I get an error.
How can you calculate the sum of the values by Python?

python - How to calculate a date back from another date with a given number of work days

I need to calculate date (year, month, day) which is (for example) 18 working days back from another date. It would be enough to eliminate just weekends.
Example: I've got a date 2009-08-21 and a number of 18 workdays as a parameter, and correct answer should be 2009-07-27.
thanks for any help

python - How to calculate the scrape URL for a torrent

I've read the Bit-torrent specification and done a number of searches, trying to find out how I can get the seeds/peers/downloaded data from a torrent tracker (using Python). I can calculate the info hash from a Torrent no problem, which matches up with the info hash given by various working torrent applications.
However, when I try to get the information from the tracker I either timeout (the tracker is working) o...

datetime - How to use Python to calculate time

I want to write python script that acts as a time calculator.
For example:
Suppose the time is now 13:05:00
I want to add 1 hour, 23 minutes, and 10 seconds to it.
and I want to print the answer out.
How do I do this in Python?
What if date is also involved?

c# - Calculate percent at runtime

I have this problem where I have to "audit" a percent of my transtactions.
If percent is 100 I have to audit them all, if is 0 I have to skip them all and if 50% I have to review the half etc.
The problem ( or the opportunity ) is that I have to perform the check at runtime.
What I tried was:
audit = 100/percent
So if percent is 50
audit = 100 /...

python - Calculate time between time-1 to time-2?

enter time-1 // eg 01:12
enter time-2 // eg 18:59
calculate: time-1 to time-2 / 12
// i.e time between 01:12 to 18:59 divided by 12
How can it be done in Python. I'm a beginner so I really have no clue where to start.
Edited to add: I don't want a timer. Both time-1 and time-2 are entered by the user manually.
Thanks in advance for your help.

python - How to calculate positions of holes in a game board?

I'm making a game with Python->PyGame->Albow and ran into a problem with board generation. However I'll try to explain the problem in a language agnostic way. I believe it's not related to python.
I've split the game board generation into several parts.
Part one generates the board holes.
Holes are contained in a list/array. Each hole object has a mapping of angles relating to other...

# Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python