# 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 the problem and calculated the speed between the last two known x and y positions using this method

```
dx = float(x) - float(a1)
dy = float(y) - float(b1)
dist = math.sqrt( math.pow(dx,2) + math.pow(dy,2))
dz = float(z) - float(c1)
speed = float(dist/dz)
```

now what rule should i follow to convert the speed to miles per hour?? thanks for all your help, this is the output in realtime..

```
speed = 1512.53949852 Time = 4:30:690187 CPUTime = 1312531470.7 X = 701 Y = 600 PX = 692 PY = 605 PT = 1312531470.69
speed = 0.0 Time = 4:30:697020 CPUTime = 1312531470.7 X = 701 Y = 600 PX = 701 PY = 600 PT = 1312531470.7
speed = 1563.45505256 Time = 4:30:703667 CPUTime = 1312531470.73 X = 734 Y = 586 PX = 701 PY = 600 PT = 1312531470.7
speed = 0.0 Time = 4:30:726614 CPUTime = 1312531470.73 X = 734 Y = 586 PX = 734 PY = 586 PT = 1312531470.73
speed = 882.257032576 Time = 4:30:735274 CPUTime = 1312531470.76 X = 753 Y = 580 PX = 734 PY = 586 PT = 1312531470.73
speed = 0.0 Time = 4:30:756930 CPUTime = 1312531470.76 X = 753 Y = 580 PX = 753 PY = 580 PT = 1312531470.76
speed = 363.108272412 Time = 4:30:764397 CPUTime = 1312531470.79 X = 762 Y = 580 PX = 753 PY = 580 PT = 1312531470.76
speed = 373.79057125 Time = 4:30:789201 CPUTime = 1312531470.8 X = 765 Y = 580 PX = 762 PY = 580 PT = 1312531470.79
speed = 92.0338354526 Time = 4:30:797211 CPUTime = 1312531470.82 X = 767 Y = 580 PX = 765 PY = 580 PT = 1312531470.8
speed = 0.0 Time = 4:30:818938 CPUTime = 1312531470.83 X = 767 Y = 580 PX = 767 PY = 580 PT = 1312531470.82
speed = 46.9571214259 Time = 4:30:826073 CPUTime = 1312531470.85 X = 767 Y = 579 PX = 767 PY = 580 PT = 1312531470.83
speed = 0.0 Time = 4:30:847362 CPUTime = 1312531470.85 X = 767 Y = 579 PX = 767 PY = 579 PT = 1312531470.85
```

Asked by:

**Kellan205**| Posted: 27-01-2022

# Answer 1

Store the start position and end position, as well as the start time and end time. Get the distance, then divide by the time. That gives you a speed. Presumably that speed is pixels per millisecond, so you just need to convert that to the units you want (miles per hour).

```
# Start
data = display.Display().screen().root.query_pointer()._data
x = data["root_x"]
y = data["root_y"]
z = time.time()
# Time passes...
# End
data = display.Display().screen().root.query_pointer()._data
x2 = data["root_x"]
y2 = data["root_y"]
z2 = time.time()
# Determine distance traveled
dx = x2 - x1
dy = y2 - y1
dist = math.sqrt( math.pow(dx, 2) + math.pow(dy, 2) ) # Distance between 2 points
# Get the change in time
dz = z2 - z1
# Print out the speed
print "I've traveled {0}".format(dist/dz)
# Convert that to the units you want
```

Answered by: **Kellan831**| Posted: 28-02-2022

# Answer 2

If you're running this in a loop, just get an initial sample before entering the loop and then take a position on each iteration, replacing the initial position with the newer one each time.

```
import math
import collections
import time
PIXEL_MILE_RATIO = 6336000 # assumes 100 pixels/inch
# you'll need to come up with a value for this
pixels_to_miles = lambda p: p*PIXEL_MILE_RATIO
Sample = collections.namedtuple('Sample', 'x,y,z')
def calculate_speed(sample1, sample2):
distance = math.sqrt((sample2.x - sample1.x)**2 + (sample2.y - sample1.y)**2)
hours = (sample2.z - sample1.z) / 3600.
return pixels_to_miles(distance)/hours
data0 = display.Display().screen().root.query_pointer()._data
sample0 = Sample(data0['root_x'], data0['root_y'], time.time()
while LOOP_CONDITIONAL:
data1 = display.Display().screen().root.query_pointer()._data
sample1 = Sample(data1['root_x'], data1['root_y'], time.time()
print 'Your mouse is moving at {} miles per hour'.format(calculate_speed(sample0, sample1))
sample0 = sample1
```

Answered by: **Arnold546**| Posted: 28-02-2022

# Answer 3

I don't know which library you're using but I would use `pygame.mouse.get_rel()`

to calculate mouse speed, it would be something easy.

**Freddie257**| Posted: 28-02-2022

# Similar questions

python - How to calculate time of mouse move?

i have this code that discribe mouse move
import sys
import math
import time
from datetime import datetime
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from toolz.itertoolz import second
class Frame:
def __init__(self, position, time):
self.position = position
self.time = time
def speed(self, frame):
d = distance(*self.position, *fra...

How Python calculate number?

This question already has answers here:

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 - 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...

How Python calculate number?

This question already has answers here:

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.

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

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