I have a model where I want to measure the time it takes for a turtle to travel at a given speed from one point to another, using the scale of the map and speed/fd movement to quantify elapsed real time.
I have speed set to a random number (global variable input on UI) for all ships and a list for each turtle with the coordinates of the path. I use the formula of time = distance / speed but cannot figure out how to count time accurately.
The speed is set to a number around 30, which I would like to use as km/h. The scale of the map is 1000m x 1000m per patch so I have tried using factors of 1000 to fix the calculation to no avail. below is my calculation for time.
to move
tick
ask ships with [length current-path != 0]
[
let x1 xcor
let x2 [pxcor] of first current-path
let y1 ycor
let y2 [pycor] of first current-path
let distance-traveled sqrt ((x2 - x1)^ 2 + (y2 - y1)^ 2)
set time ((distance-traveled * meters-per-patch) / (speed)
set timelist lput time timelist
set totaltime sum timelist
go-to-next-patch-in-current-path
]
end
This potion calls the movement. I am divding speed/1000 since the number for speed is in the 10's and I want the turtles to move much less than 1 patch each tick to allow it to land directly on the patch coordinates in the list.
to go-to-next-patch-in-current-path
face first current-path
ifelse distance first current-path < .1
[
move-to first current-path
set current-path remove-item 0 current-path
]
[
fd speed / 1000
set heading towards first current-path
]
end
Any help would be greatly appreciated, thanks a lot.
Regardless. If you want someone to move from x1,y1 to x2,y2. You need to calculate the distance to x2 y2. Suppose you want it to take 4 seconds to move from x1,y1 to x2,y2
For a turtle:
on your setup or when you arrive at x1,y1
let t 3
let d distancexy x2 y2
let velocity d / t
facexy x2 y2
while you're not at x2,y2
fd velocity
I think your problem is at every iteration you're recalculating your velocity. You're saying if you're 5 meters away, and want to take 5 seconds, move 1 meter. Then in the next time unit, you'll be 4 meters away and want to take 5 seconds, move .8 meters. etc
Related
I am a biologist and applying for a job, for which I need to solve this question. It is an open book test, where the internet and any other resources are fair game. Here's the question - I'm stuck on how to approach it and would appreciate pointers. My intuition is posted underneath.
Background
Your neighbor is a farmer with two cows, Clarabelle and Bernadette. Each cow has its own square pen that is 11m on a side (see first figure). The farmer is heading out of town for a trip and plans to leave the cows in their respective pens, which are completely filled with grass to start. The cows begin in the center of the pen, and will slowly move around the pen eating the grass. They move around the pen very slowly, always pausing to eat or rest after every step. If you divide the pen into 1m squares, the cows can move one square in any direction each step (like a king on a chess board), as shown in the second figure.
After each move, the cow will spend 20 minutes in the new square eating grass, if it is available. Once the grass in a square is eaten, it is gone forever. If the cow moves to a square whose grass was already eaten, then the cow will spend 20 minutes resting in that square. After 20 minutes, whether resting or eating, the cow moves to another square. If a cow is in a square adjacent to the fence, she will never try to move in the direction of the fence. The cows never stay in the same square twice in a row -- they always move to a different one after resting or eating. The first figure shows an example of what a pen might look like after some hours, with the brown spots indicating squares that have been grazed.
The first cow, Clarabelle, has no preference for direction when she moves. She is equally likely to move in any direction at all times. Let p be the probability that she moves in a direction, as shown in the first figure below.
The second cow, Bernadette, prefers to move towards squares with grass. She is twice as likely to move towards a space that has grass as she is towards a space that she has already eaten, as shown in the second figure below.
Questions
If the farmer returns after 48 hours, what percentage of the grass in her pen do you expect Clarabelle to have eaten?
How long do you expect it will take for Bernadette to eat 50% of the grass in her pen?
Suppose that if either of the cows go 24 hours without eating any grass, she will die. Which cow is expected to survive longer?
My intuition
This appears to be modeling a random walk through a 2 dimensional grid. I can for instance figure out the probability of being at a particular node in the grid, after a given time. But I'm not sure how to think about the area covered by the cow as it walks through. Would appreciate any insights.
Edit: The final aim here would be for me to write some sort of a program for this. This isn't a purely mathematics question and thus the post here.
Here is a way of computing the probabilities (for Clarabelle):
Start with a grid of 0, except 1 on the (6, 6) cell, this is your probability grid for time t = 0.
At time t + 1, the probability p(x, y, t + 1) of being on cell (x, y) is given by: p(x, y, t + 1) = p1 * p(x + 1, y, t) + p2 * p(x + 1, y - 1, t) + ... (you have eight term in the sum).
Note that all the pi are not equals: the probability can be 1/3 (corner), 1/5 (edge), or 1/8 (any other cell).
You can dynamically update your grid by running this for each step t = 0 to t = 144 (48h).
If you want to know the probability for a cell already been eaten, it is simply 1 - Pn where Pn if the probability of the cell never been visited, which is:
(1 - p(x, y, 0)) * (1 - p(x, y, 1)) * (1 - p(x, y, 2)) * ...
Here is a code that compute these probability using numpy in Python (basically, this is considering a Markov Chain where the state X is the set of all cells |X| = 121, and the transition matrix T = {Tij} where Tij is the probability of moving from i to j):
GridSize = 11
TranSize = GridSize * GridSize
T_Matrix = np.zeros((TranSize, TranSize), dtype = float)
for u in range(T_Matrix.shape[0]):
for v in range(T_Matrix.shape[1]):
ux, uy = u % GridSize, u // GridSize
vx, vy = v % GridSize, v // GridSize
if u == v or abs(ux - vx) > 1 or abs(uy - vy) > 1:
p = 0
elif (ux == 0 or ux == 10) and (uy == 0 or uy == 10):
p = 1/3
elif ux == 0 or ux == 10 or uy == 10 or uy == 0:
p = 0.2
else:
p = 0.125
T_Matrix[u, v] = p
pxy = np.zeros((TranSize, ), dtype = float)
pxy[11 * 5 + 5] = 1
eat = 1 - pxy
for _ in range(144):
pxy = pxy.dot(T_Matrix)
eat *= (1 - pxy)
print((1 - eat).reshape((GridSize, GridSize)))
The algorithm for Bernadette is a bit more complex because your p1, p2, ... are probabilistic, so you get two terms for each adjacent cell.
Once you have all these probabilities, you can easily find what you want.
There are two ways to approach such problems: analytically or via simulation.
If you'll simulate the process using a Monte-Carlo based method, you can easily find the answers by averaging the results of many trails.
I would assume that this is what you're expected to do, unless you were guided otherwise.
I am writing a simulation in which an object moves in a 2D world towards a target position, stored as vector target(x,y). The object position is stored as position vector pos(x,y) as well. The object contains two more vectors, the desired movement velocity dv(x,y), as well as the current movement velocity cv(x,y). At the start of the simulation both these velocity vectors are initial, i.e. set to (0,0).
When the object should move towards the target position, I calcuate the desired velocity vector dv, normalize it, and scale it by a movement speed value:
dv.set(target).sub(pos).normalize()
dv.scale(speed)
I want to make the movement look more realistic, that's why I use two velocity vectors. dv tells the full speed I want to move the object, and cv holds the real speed the object currently moves at.
Then at each frame (update step) the current velocity cv is set based on the desired velocity dv and an acceleration value acc. This is done by simply calculating the difference between cv and dv and clamping this difference to acc. That way the object starts to move slowly and accelerates gradually to eventually reach full speed.
So far this is working fine. Now I want to make use of acc for deceleration as well. When the distance between pos and target is at a certain value, the desired velocity dv should be set to (0,0), so that the object gradually decelerates until it comes to a full stop at the target position.
My question is: How can I calculate at which distance I need to set dv to (0,0) (i.e. tell the system to stop movement), so that the object decelerates correctly to stop exactly at the target position?
Use the kinematic equations:
vf2 = vi2 + 2 * a * d
vf is your final velocity, or 0 (the speed you want to be going)
vi is your initial velocity, given (the speed your object is currently moving).
a is acceleration
d is distance.
Solve for d:
2*a*d = vf2 - vi2
2*a*d = 0 - vi2
assume acceleration is negative, so multiply both sides by -1
2*|a|*d = vi2
|a| is the absolute value of your acceleration (deceleration in your case)
d = vi2 / (2*|a|)
You're doing a discrete time simulation of motion. One way to keep things simple is to perform the calculations in a way that makes acceleration and deceleration symmetrical. In other words, the distance traveled while accelerating should be the same as the distance traveled while decelerating. As an example, assume
acceleration is 5
top speed is 13
the object begins decelerating as soon as it reaches top speed
Here's how the discrete time simulation would progress
first tick
old speed = 0
new speed = 5
distance = 5
second tick
old speed = 5
new speed = 10
distance = 15
third tick
old speed = 10
new speed = 13
distance = 28 <-- total distance while accelerating
fourth tick
old speed = 13
distance = 41
new speed = 10 <-- not 8!!!
fifth tick
old speed = 10
distance = 51
new speed = 5
sixth tick
old speed = 5
distance = 56 <-- Yay, twice the distance, we have symmetry
new speed = 0
There are two key points here
While accelerating the speed is updated first and then the distance is updated. While decelerating the order is reversed, the distance is updated first, and then the speed.
When decelerating, it's important to keep the adjusted speed as a multiple of the acceleration
In the C programming language, the following code could be used to update the speed during deceleration
if ( old_speed % acceleration != 0 ) // if speed is not a multiple of acceleration
new_speed = old_speed - old_speed % acceleration; // reduce speed to a multiple of acceleration
else // otherwise
new_speed = old_speed - acceleration; // reduce speed by acceleration
If acceleration and deceleration are symmetrical, then computing the deceleration distance is the same as computing the acceleration distance.
distance = acceleration * (1+2+3+ ... +N) + fudge_factor
where
N is top_speed / acceleration truncated to an integer, e.g. 13/5 ==> 2
fudge_factor is 0 if top speed is a multiple of acceleration, or
top_speed otherwise
The computation can be simplified by noting that
1+2+3+ ... +N = N * (N+1) / 2
In C, the total distance travelled while decelerating could be computed as follows
int top_speed = 13;
int acceleration = 5;
int N = top_speed / acceleration; // Note: in C, integer division truncates
int fudge = 0;
if ( top_speed % acceleration != 0 )
fudge = top_speed;
int distance = acceleration * (N * (N+1)) / 2 + fudge;
This problem is based on a puzzle by Joel Spolsky from 2001.
A guy "gets a job as a street painter, painting the dotted lines down the middle of the road." On the first day he finishes up 300 yards, on the second - 150, and on the 3rd even less so. The boss is furious and demands an explanation.
"I can't help it," says the guy. "Every day I get farther and farther away from the paint can!"
My question is, can you estimate the distance he covered in the 3rd day?
One of the comments in the linked thread does derive a precise solution, but my question is about a good enough estimation -- say, 10% -- that is easy to make from the general principles.
clarification: this is about a certain method in analysis of algorithms, not about developing an algorithm, nor code.
There are a lot of unknowns here - his walking speed, his painting speed, for how long does the paint in the brush last...
But clearly there are two processes going on here. One is quadratic - it's the walking to and fro between the paint can and the painting point. The other is linear - it's the process of painting, itself.
Thinking about the 10th or even the 100th day, it is clear that the linear component becomes negligible, and the process becomes very nearly quadratic - the walking takes almost all the time. During the first few minutes of the first day, on the contrary, it is close to being linear.
We can thus say that the time t as a function of the distance s follows a power law t ~ s^a with a changing coefficient a = 1.0 ... 2.0. This also means that s ~ t^b, b = 1/a.
Applying the empirical orders of growth analysis:
The b coefficient between day 1 and day 2 is approximated as
b(1,2) = log (450/300) / log 2 = 0.585 ;; and so,
a(1,2) = 1/b(1,2) = 1/0.585 = 1.71
Just as expected, the a coefficient is below 2. Going for the time period between day 2 and day 3, we can set it approximately to the middle value between 1.71 and 2.0,
a(2,3) = 1.85 ;; a = 1.0 .... 2.0
b(2,3) = 0.54 ;; b = 1.0 .... 0.5
s(3) = s(2) * (3/2)^b(2,3)
= 450 * (3/2)^0.54
= 560 yards
Thus the distance covered in the third day can be estimated as 560 - 450 = 110 yards.
What if the a coefficient had the maximum possible value, 2.0, already (which is impossible)? Then, 450*(3/2)^0.5 = 551 yards. And for the other extreme, if it were the same 1.71 (which it clearly can't be, either), 450*(3/2)^0.585 = 570.
This means that the estimate of 110 yards is plausible, with an error of less than 10 yards on either side.
considering four assumptions :-
painting speed = infinity
walking speed = x
he can paint only infinitly small in one brush stroke.
he leaves his can at starting point.
The distance he walks for painting dy road at y distance = 2y
Total distance he walks = intgeration of 2y*dy = y^2 = y^2
Total time he can paint y distance = y^2/x
Time taken to paint 300 yards = 1 day
(300)^2/x = 1
x = 90000 yards/day
Total time he can paint distance y = y^2/90000
(y/300)^2 = 2 after second day
y = 300*2^(1/2) = 424
Day 1 = 300
Day 2 = 424-300 = 124
Day 3 = 300*3^(1/2)-424 = 520 - 424 = 96
Ans : 300/124/96 assuming the first day its 300
I have a circle divided into fourths. I need an algorithm that can rotate the circle from one position to another in the most efficient way.
The "trays" are named 1 to 4.
I now use the algoritm:
int degrees = (currentPos - newPos) * 90;
using the algorithm i get how many degrees i need to rotate the circle to get to the new position. However if i am in position 4 and need to go to 1, the result will be 4 - 1 * 90 = 270. In this case the most efficient would be to rotate -90 instead of 270. (the same goes for moving from 1 to 4).
Anyone got a good idea of how to do this? I can of course use an if statement:
if(degrees >= -180 && degrees <= 180)
sortingTrayMotor.rotate(degrees);
else if(degrees == -270)
sortingTrayMotor.rotate(90);
else
sortingTrayMotor.rotate(-90);
I guess there is a better way to do it though with some mod operation.
Exactly what you're doing, only if the result is > 180 degrees, subtract 360 degrees.
Given..
1 - The start-point GPS coordinates,
2 - The end-point GPS coordinates,
3 - The speed at which the object is travelling,
4 - Knowing that the trip trajectory will be a straight line...
How can I calculate what my GPS coordinated will be in n minutes' time? That is to say, how can I calculate my position at a given time after the trip has started before the trip has ended?
You need to use the Thaddeus Vincenty Formulae
This will give you the distance between two GPS co-ordinates (lon/lat).
Then simply do
Time = [Distance] in m / [Speed] in m/s
Assuming uniform speed, its a gross estimation.
This method is accurate enough only for small distances, because the curvature of the Earth is not accounted for. You can convert pseudo-spherical coordinates to planar coordinates, but a different method would probably be better for cases where the distance is large and accuracy is needed.
The key is to calculate the total distance between the start and end points. You can use Euclidean distance but, as stated, this is reasonably accurate only for smaller distances:
distance = sqrt((end.x - start.x) ** 2 + (end.y - start.y) ** 2)
You then know how long it will take to travel the entire distance:
timeToTravelDistance = distance / speed
From this, you can calculate the percentage of the distance you have traveled from start to end given time:
percentageTraveled = time / timeToTravelDistance
Finally, interpolate:
result.x = start.x * (1 - percentageTraveled) + end.x * percentageTraveled
result.y = start.y * (1 - percentageTraveled) + end.y * percentageTraveled