Generate points for smooth movement between two given pointsC# code to derive tangential points between two circles to create a trapezoidChecking for intersection pointsDistance between angles as points“Critter Tracking: When does it cross its own path?”“Critter Tracking: When does it cross its own path?” Part 2Get all points within given radius for a given vectorCalculating distance and angle between two points, C# programClosest distance between points in a list
How could it be that the capo isn't changing the pitch?
Do mortgage points get applied directly to the principal?
Finder/Terminal: Find files that contain less than 21 lines of text
How do you manage to study and have a balance in your life at the same time?
Why did the VIC-II and SID use 6 µm technology in the era of 3 µm and 1.5 µm?
Why do we need explainable AI?
What is the difference between "wie" and "nach" in "Klingt wie/nach..."
In-universe, why does Doc Brown program the time machine to go to 1955?
std::tuple sizeof, is it a missed optimization?
When is it legal to castle moving the rook first?
Case Studies and Real Problems for Teaching Optimization and Modelling
What does "se jouer" mean here?
Why don't they build airplanes from 3D printer plastic?
First Number to Contain Each Letter
What functional purpose does endorsing a candidate serve?
Generate points for smooth movement between two given points
Main differences between 5th edition Druid and 3.5 edition Druid
Too many SOQL Queries when inserting records
Everyone for non livings
Would you recommend a keyboard for beginners with or without lights in keys for learning?
Which is the best password hashing algorithm in .NET Core?
Are there photos of the Apollo LM showing disturbed lunar soil resulting from descent engine exhaust?
Global variables and information security
Why do old games use flashing as means of showing damage?
Generate points for smooth movement between two given points
C# code to derive tangential points between two circles to create a trapezoidChecking for intersection pointsDistance between angles as points“Critter Tracking: When does it cross its own path?”“Critter Tracking: When does it cross its own path?” Part 2Get all points within given radius for a given vectorCalculating distance and angle between two points, C# programClosest distance between points in a list
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
$begingroup$
This is one of the methods in a project for generating points between two given points. We add points of route with a 25ms delay in an array and a camera on Google Maps is always at the last point. So we need to move it smoothly. This method adds those extra points between any two given points to make it move smoothly.
public List<Tuple<double, double>> GeneratePointsForSmoothMovement(double x1, double y1, double x2, double y2, double divider)
// If points are same, return empty list
if (x1 == x2 && y1 == y2)
return new List<Tuple<double, double>>();
// get difference between x and y cordinates
double xi = (x2 - x1);
double yi = (y2 - y1);
// divide difference into n parts
xi = xi / divider;
yi = yi / divider;
// set new temp vars equal to first point
double xf = x1;
double yf = y1;
// initialize list to save new points
List<Tuple<double, double>> points = new List<Tuple<double, double>>();
// increment temp vars by difference-division parts
for (int i = 0; i < divider; i++)
xf += xi;
yf += yi;
points.Add(Tuple.Create(xf, yf));
// last cordinate in the list will be equal to point 2
// return
return points;
Is this the most efficient way ?
c# computational-geometry google-maps easing
New contributor
Waleed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
add a comment |
$begingroup$
This is one of the methods in a project for generating points between two given points. We add points of route with a 25ms delay in an array and a camera on Google Maps is always at the last point. So we need to move it smoothly. This method adds those extra points between any two given points to make it move smoothly.
public List<Tuple<double, double>> GeneratePointsForSmoothMovement(double x1, double y1, double x2, double y2, double divider)
// If points are same, return empty list
if (x1 == x2 && y1 == y2)
return new List<Tuple<double, double>>();
// get difference between x and y cordinates
double xi = (x2 - x1);
double yi = (y2 - y1);
// divide difference into n parts
xi = xi / divider;
yi = yi / divider;
// set new temp vars equal to first point
double xf = x1;
double yf = y1;
// initialize list to save new points
List<Tuple<double, double>> points = new List<Tuple<double, double>>();
// increment temp vars by difference-division parts
for (int i = 0; i < divider; i++)
xf += xi;
yf += yi;
points.Add(Tuple.Create(xf, yf));
// last cordinate in the list will be equal to point 2
// return
return points;
Is this the most efficient way ?
c# computational-geometry google-maps easing
New contributor
Waleed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
$begingroup$
What is your question?
$endgroup$
– Olivier Jacot-Descombes
9 hours ago
$begingroup$
@OlivierJacot-Descombes this website is for code review and improvements suggestion right?
$endgroup$
– Waleed
8 hours ago
2
$begingroup$
Are you questioning the interpolation method, the code quality, memory or time efficiency, correctness or something, else?
$endgroup$
– Olivier Jacot-Descombes
8 hours ago
add a comment |
$begingroup$
This is one of the methods in a project for generating points between two given points. We add points of route with a 25ms delay in an array and a camera on Google Maps is always at the last point. So we need to move it smoothly. This method adds those extra points between any two given points to make it move smoothly.
public List<Tuple<double, double>> GeneratePointsForSmoothMovement(double x1, double y1, double x2, double y2, double divider)
// If points are same, return empty list
if (x1 == x2 && y1 == y2)
return new List<Tuple<double, double>>();
// get difference between x and y cordinates
double xi = (x2 - x1);
double yi = (y2 - y1);
// divide difference into n parts
xi = xi / divider;
yi = yi / divider;
// set new temp vars equal to first point
double xf = x1;
double yf = y1;
// initialize list to save new points
List<Tuple<double, double>> points = new List<Tuple<double, double>>();
// increment temp vars by difference-division parts
for (int i = 0; i < divider; i++)
xf += xi;
yf += yi;
points.Add(Tuple.Create(xf, yf));
// last cordinate in the list will be equal to point 2
// return
return points;
Is this the most efficient way ?
c# computational-geometry google-maps easing
New contributor
Waleed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
This is one of the methods in a project for generating points between two given points. We add points of route with a 25ms delay in an array and a camera on Google Maps is always at the last point. So we need to move it smoothly. This method adds those extra points between any two given points to make it move smoothly.
public List<Tuple<double, double>> GeneratePointsForSmoothMovement(double x1, double y1, double x2, double y2, double divider)
// If points are same, return empty list
if (x1 == x2 && y1 == y2)
return new List<Tuple<double, double>>();
// get difference between x and y cordinates
double xi = (x2 - x1);
double yi = (y2 - y1);
// divide difference into n parts
xi = xi / divider;
yi = yi / divider;
// set new temp vars equal to first point
double xf = x1;
double yf = y1;
// initialize list to save new points
List<Tuple<double, double>> points = new List<Tuple<double, double>>();
// increment temp vars by difference-division parts
for (int i = 0; i < divider; i++)
xf += xi;
yf += yi;
points.Add(Tuple.Create(xf, yf));
// last cordinate in the list will be equal to point 2
// return
return points;
Is this the most efficient way ?
c# computational-geometry google-maps easing
c# computational-geometry google-maps easing
New contributor
Waleed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Waleed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
edited 8 hours ago
dfhwze
10.8k2 gold badges19 silver badges71 bronze badges
10.8k2 gold badges19 silver badges71 bronze badges
New contributor
Waleed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
asked 9 hours ago
WaleedWaleed
1213 bronze badges
1213 bronze badges
New contributor
Waleed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Waleed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$begingroup$
What is your question?
$endgroup$
– Olivier Jacot-Descombes
9 hours ago
$begingroup$
@OlivierJacot-Descombes this website is for code review and improvements suggestion right?
$endgroup$
– Waleed
8 hours ago
2
$begingroup$
Are you questioning the interpolation method, the code quality, memory or time efficiency, correctness or something, else?
$endgroup$
– Olivier Jacot-Descombes
8 hours ago
add a comment |
$begingroup$
What is your question?
$endgroup$
– Olivier Jacot-Descombes
9 hours ago
$begingroup$
@OlivierJacot-Descombes this website is for code review and improvements suggestion right?
$endgroup$
– Waleed
8 hours ago
2
$begingroup$
Are you questioning the interpolation method, the code quality, memory or time efficiency, correctness or something, else?
$endgroup$
– Olivier Jacot-Descombes
8 hours ago
$begingroup$
What is your question?
$endgroup$
– Olivier Jacot-Descombes
9 hours ago
$begingroup$
What is your question?
$endgroup$
– Olivier Jacot-Descombes
9 hours ago
$begingroup$
@OlivierJacot-Descombes this website is for code review and improvements suggestion right?
$endgroup$
– Waleed
8 hours ago
$begingroup$
@OlivierJacot-Descombes this website is for code review and improvements suggestion right?
$endgroup$
– Waleed
8 hours ago
2
2
$begingroup$
Are you questioning the interpolation method, the code quality, memory or time efficiency, correctness or something, else?
$endgroup$
– Olivier Jacot-Descombes
8 hours ago
$begingroup$
Are you questioning the interpolation method, the code quality, memory or time efficiency, correctness or something, else?
$endgroup$
– Olivier Jacot-Descombes
8 hours ago
add a comment |
4 Answers
4
active
oldest
votes
$begingroup$
The
Tuple<T1, T2>type is a reference type requiring to create objects on the heap, what puts strain on the GC. Use a value type, i.e. a struct type. Use the newValueTupletype or an existing point or vector type or create your own struct. In public API's dedicated types are preferred over tuple types.You are testing
x1 == x2 && y1 == y2. This is a bit hazardous, sincedoublevalues are subject to tiny rounding errors. Define a minimum allowed difference.private const double Eps = 1e-6;
if (Math.Abs(x2 - x1) < Eps && Math.Abs(y2 - y1) < Eps)Parentheses are superfluous here. The assignment operator has always the lowest precedence (except sequential evaluation with
,).double xi = x2 - x1;You could make the divider dependent on the distance between the points. Doing this creates a more uniform camera speed. If you want to keep the original relative speeds, don't do this.
Don't repeat long type names. Use
varinstead.var points = new List<Tuple<double, double>>();When to use
varis a matter of preference. My rules are:- If the type is explicitly visible (as here after the
newkeyword), usevar. - Don't use
varfor primitive types likeint,string, ordouble. - LINQ expressions often return complex nested types involving
IOrderedEnumerableandIGroupingetc. nobody wants to know. These types a mostly used for temporary results either. Usevarhere. - Anonymous types have no name and require
var.var a = new Id = 1, Value = 1.4 ;. It's the main reason thevarkeyword has been introduced.
- If the type is explicitly visible (as here after the
$endgroup$
$begingroup$
Do you see a case for the parentheses for readability?
$endgroup$
– dfhwze
8 hours ago
1
$begingroup$
Parentheses can enhance readability if the expression mixes different types of operators like shift operators, arithmetic operators and others, where the operator precedence might not be obvious at a first glance, since C# has a lot of levels of precedence. In this specific case, I don’t see any advantage for parentheses.
$endgroup$
– Olivier Jacot-Descombes
7 hours ago
1
$begingroup$
I do see advantage in parenthesses. You don't have to remember the operator precedence and any differences between languagues. You just set them the way you want them to work and you're done. No need to study the docs. cc @dfhwze :P
$endgroup$
– t3chb0t
7 hours ago
1
$begingroup$
@t3chb0t I've had several discussions about the use of parentheses. And in the end we could argue that: (raganwald.com/2016/03/17/…).
$endgroup$
– dfhwze
7 hours ago
add a comment |
$begingroup$
Make it an enumerator You can make the evaluation lazy and get rid of the intermediate list by changing the return type to IEnumerable<>.
Use named tuples You can make the API more user-friendly by using named tuples. Something like a readonly struct Point would be preferable but if you don't have it or don't want it then named tuples are your best friend.
Interpolation The point generation you're doing is called interpolation. You can use this word in the method name like InterpolateMovement. I don't know if these calculations have any concrete name, but if they have than you may use an even more exact name like InterpolateMovementByAlgorithmName.
Here's an example of how this could look like after implementing the above suggesions:
public IEnumerable<(double X, double Y)> InterpolateMovement(double x1, double y1, double x2, double y2, double divider)
// If points are same, return empty list
if (x1 == x2 && y1 == y2)
yield break; // break the enumeration
// ..
// increment temp vars by difference-division parts
for (int i = 0; i < divider; i++)
xf += xi;
yf += yi;
yield return (xf, yf); // <-- return tuples
$endgroup$
3
$begingroup$
Linear interpolation
$endgroup$
– Henrik Hansen
8 hours ago
add a comment |
$begingroup$
The parameter name divider doesn't say much. I think I would call it numPoints or countOfPoints or numOffsets.
List<Tuple<double, double>> points = new List<Tuple<double, double>>();
You know the size of the list, so to improve performance you can set the capacity of the list
List<Tuple<double, double>> points = new List<Tuple<double, double>>(divider);
double xi = (x2 - x1);
double yi = (y2 - y1);
// divide difference into n parts
xi = xi / divider;
yi = yi / divider;
can be done more elegantly:
double xi = (x2 - x1) / divider;
double yi = (y2 - y1) / divider;
$endgroup$
add a comment |
$begingroup$
Dividor
dividor is ill-defined. It acts as a factor for quantization:
xi = xi / divider;
But also as threshold for yielding smoothed results:
for (int i = 0; i < divider; i++)
While this seems fine if dividor is $integer >= 2$, it could yield unwanted results for fractions (as it is a double precision integer). I would at least change its type to int or uint instead and add an out-of-bound guard. If you would decide to allow fractions, make it clear in the spec how the edge case near the end is handled, since you might get a scenario where you don't synchronize with the end value.
Usability
GeneratePointsForSmoothMovement is a low level generator. The caller code should still think about technical parameters to provide. And if a caller requires several levels of smoothness, multiple calls with different parameters have to be executed. In order to provide the consumer a solution that avoids most overhead, you could write an extension method on IEnumerable<Tuple<Double,Double>> and preferrably also on IDictionary<Double,Double> for faster lookup.
In pseudo code:
public static Fun<Double, Double> ToContinuousFunction(
this IDictionary<Double,Double> points)
return new Function<Double, Double>(x =>
if (points.TryGetValue(x, out var y))
return y;
// .. perform lineair interpolation or extrapolation based on nearby points
);
Let's say we have points (x: 1, y: 10) and (x: 2, y: 20):
var f = points.ToContiniousFunction();
var yValues = new []
f(1) // 10 (from cache)
,f(1.5) // 15 (interpolation)
,f(2) // 20 (from cache)
,f(3) // 30 (extrapolation)
;
$endgroup$
$begingroup$
Very acute observation.
$endgroup$
– Henrik Hansen
6 hours ago
1
$begingroup$
@HenrikHansen there is actually a very nice pattern you can make here by wrapping a dictionary of (double,double) in a function that performs inter- and extrapolation when a requested value is not cached in the dic. this way you could do var f = pointsDic.ToFunction(); var x = 1.16f; var y = f(x); etc without having to worry whether x is observed in the dictionary.
$endgroup$
– dfhwze
6 hours ago
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Waleed is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f227404%2fgenerate-points-for-smooth-movement-between-two-given-points%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
The
Tuple<T1, T2>type is a reference type requiring to create objects on the heap, what puts strain on the GC. Use a value type, i.e. a struct type. Use the newValueTupletype or an existing point or vector type or create your own struct. In public API's dedicated types are preferred over tuple types.You are testing
x1 == x2 && y1 == y2. This is a bit hazardous, sincedoublevalues are subject to tiny rounding errors. Define a minimum allowed difference.private const double Eps = 1e-6;
if (Math.Abs(x2 - x1) < Eps && Math.Abs(y2 - y1) < Eps)Parentheses are superfluous here. The assignment operator has always the lowest precedence (except sequential evaluation with
,).double xi = x2 - x1;You could make the divider dependent on the distance between the points. Doing this creates a more uniform camera speed. If you want to keep the original relative speeds, don't do this.
Don't repeat long type names. Use
varinstead.var points = new List<Tuple<double, double>>();When to use
varis a matter of preference. My rules are:- If the type is explicitly visible (as here after the
newkeyword), usevar. - Don't use
varfor primitive types likeint,string, ordouble. - LINQ expressions often return complex nested types involving
IOrderedEnumerableandIGroupingetc. nobody wants to know. These types a mostly used for temporary results either. Usevarhere. - Anonymous types have no name and require
var.var a = new Id = 1, Value = 1.4 ;. It's the main reason thevarkeyword has been introduced.
- If the type is explicitly visible (as here after the
$endgroup$
$begingroup$
Do you see a case for the parentheses for readability?
$endgroup$
– dfhwze
8 hours ago
1
$begingroup$
Parentheses can enhance readability if the expression mixes different types of operators like shift operators, arithmetic operators and others, where the operator precedence might not be obvious at a first glance, since C# has a lot of levels of precedence. In this specific case, I don’t see any advantage for parentheses.
$endgroup$
– Olivier Jacot-Descombes
7 hours ago
1
$begingroup$
I do see advantage in parenthesses. You don't have to remember the operator precedence and any differences between languagues. You just set them the way you want them to work and you're done. No need to study the docs. cc @dfhwze :P
$endgroup$
– t3chb0t
7 hours ago
1
$begingroup$
@t3chb0t I've had several discussions about the use of parentheses. And in the end we could argue that: (raganwald.com/2016/03/17/…).
$endgroup$
– dfhwze
7 hours ago
add a comment |
$begingroup$
The
Tuple<T1, T2>type is a reference type requiring to create objects on the heap, what puts strain on the GC. Use a value type, i.e. a struct type. Use the newValueTupletype or an existing point or vector type or create your own struct. In public API's dedicated types are preferred over tuple types.You are testing
x1 == x2 && y1 == y2. This is a bit hazardous, sincedoublevalues are subject to tiny rounding errors. Define a minimum allowed difference.private const double Eps = 1e-6;
if (Math.Abs(x2 - x1) < Eps && Math.Abs(y2 - y1) < Eps)Parentheses are superfluous here. The assignment operator has always the lowest precedence (except sequential evaluation with
,).double xi = x2 - x1;You could make the divider dependent on the distance between the points. Doing this creates a more uniform camera speed. If you want to keep the original relative speeds, don't do this.
Don't repeat long type names. Use
varinstead.var points = new List<Tuple<double, double>>();When to use
varis a matter of preference. My rules are:- If the type is explicitly visible (as here after the
newkeyword), usevar. - Don't use
varfor primitive types likeint,string, ordouble. - LINQ expressions often return complex nested types involving
IOrderedEnumerableandIGroupingetc. nobody wants to know. These types a mostly used for temporary results either. Usevarhere. - Anonymous types have no name and require
var.var a = new Id = 1, Value = 1.4 ;. It's the main reason thevarkeyword has been introduced.
- If the type is explicitly visible (as here after the
$endgroup$
$begingroup$
Do you see a case for the parentheses for readability?
$endgroup$
– dfhwze
8 hours ago
1
$begingroup$
Parentheses can enhance readability if the expression mixes different types of operators like shift operators, arithmetic operators and others, where the operator precedence might not be obvious at a first glance, since C# has a lot of levels of precedence. In this specific case, I don’t see any advantage for parentheses.
$endgroup$
– Olivier Jacot-Descombes
7 hours ago
1
$begingroup$
I do see advantage in parenthesses. You don't have to remember the operator precedence and any differences between languagues. You just set them the way you want them to work and you're done. No need to study the docs. cc @dfhwze :P
$endgroup$
– t3chb0t
7 hours ago
1
$begingroup$
@t3chb0t I've had several discussions about the use of parentheses. And in the end we could argue that: (raganwald.com/2016/03/17/…).
$endgroup$
– dfhwze
7 hours ago
add a comment |
$begingroup$
The
Tuple<T1, T2>type is a reference type requiring to create objects on the heap, what puts strain on the GC. Use a value type, i.e. a struct type. Use the newValueTupletype or an existing point or vector type or create your own struct. In public API's dedicated types are preferred over tuple types.You are testing
x1 == x2 && y1 == y2. This is a bit hazardous, sincedoublevalues are subject to tiny rounding errors. Define a minimum allowed difference.private const double Eps = 1e-6;
if (Math.Abs(x2 - x1) < Eps && Math.Abs(y2 - y1) < Eps)Parentheses are superfluous here. The assignment operator has always the lowest precedence (except sequential evaluation with
,).double xi = x2 - x1;You could make the divider dependent on the distance between the points. Doing this creates a more uniform camera speed. If you want to keep the original relative speeds, don't do this.
Don't repeat long type names. Use
varinstead.var points = new List<Tuple<double, double>>();When to use
varis a matter of preference. My rules are:- If the type is explicitly visible (as here after the
newkeyword), usevar. - Don't use
varfor primitive types likeint,string, ordouble. - LINQ expressions often return complex nested types involving
IOrderedEnumerableandIGroupingetc. nobody wants to know. These types a mostly used for temporary results either. Usevarhere. - Anonymous types have no name and require
var.var a = new Id = 1, Value = 1.4 ;. It's the main reason thevarkeyword has been introduced.
- If the type is explicitly visible (as here after the
$endgroup$
The
Tuple<T1, T2>type is a reference type requiring to create objects on the heap, what puts strain on the GC. Use a value type, i.e. a struct type. Use the newValueTupletype or an existing point or vector type or create your own struct. In public API's dedicated types are preferred over tuple types.You are testing
x1 == x2 && y1 == y2. This is a bit hazardous, sincedoublevalues are subject to tiny rounding errors. Define a minimum allowed difference.private const double Eps = 1e-6;
if (Math.Abs(x2 - x1) < Eps && Math.Abs(y2 - y1) < Eps)Parentheses are superfluous here. The assignment operator has always the lowest precedence (except sequential evaluation with
,).double xi = x2 - x1;You could make the divider dependent on the distance between the points. Doing this creates a more uniform camera speed. If you want to keep the original relative speeds, don't do this.
Don't repeat long type names. Use
varinstead.var points = new List<Tuple<double, double>>();When to use
varis a matter of preference. My rules are:- If the type is explicitly visible (as here after the
newkeyword), usevar. - Don't use
varfor primitive types likeint,string, ordouble. - LINQ expressions often return complex nested types involving
IOrderedEnumerableandIGroupingetc. nobody wants to know. These types a mostly used for temporary results either. Usevarhere. - Anonymous types have no name and require
var.var a = new Id = 1, Value = 1.4 ;. It's the main reason thevarkeyword has been introduced.
- If the type is explicitly visible (as here after the
edited 7 hours ago
answered 8 hours ago
Olivier Jacot-DescombesOlivier Jacot-Descombes
3,03512 silver badges20 bronze badges
3,03512 silver badges20 bronze badges
$begingroup$
Do you see a case for the parentheses for readability?
$endgroup$
– dfhwze
8 hours ago
1
$begingroup$
Parentheses can enhance readability if the expression mixes different types of operators like shift operators, arithmetic operators and others, where the operator precedence might not be obvious at a first glance, since C# has a lot of levels of precedence. In this specific case, I don’t see any advantage for parentheses.
$endgroup$
– Olivier Jacot-Descombes
7 hours ago
1
$begingroup$
I do see advantage in parenthesses. You don't have to remember the operator precedence and any differences between languagues. You just set them the way you want them to work and you're done. No need to study the docs. cc @dfhwze :P
$endgroup$
– t3chb0t
7 hours ago
1
$begingroup$
@t3chb0t I've had several discussions about the use of parentheses. And in the end we could argue that: (raganwald.com/2016/03/17/…).
$endgroup$
– dfhwze
7 hours ago
add a comment |
$begingroup$
Do you see a case for the parentheses for readability?
$endgroup$
– dfhwze
8 hours ago
1
$begingroup$
Parentheses can enhance readability if the expression mixes different types of operators like shift operators, arithmetic operators and others, where the operator precedence might not be obvious at a first glance, since C# has a lot of levels of precedence. In this specific case, I don’t see any advantage for parentheses.
$endgroup$
– Olivier Jacot-Descombes
7 hours ago
1
$begingroup$
I do see advantage in parenthesses. You don't have to remember the operator precedence and any differences between languagues. You just set them the way you want them to work and you're done. No need to study the docs. cc @dfhwze :P
$endgroup$
– t3chb0t
7 hours ago
1
$begingroup$
@t3chb0t I've had several discussions about the use of parentheses. And in the end we could argue that: (raganwald.com/2016/03/17/…).
$endgroup$
– dfhwze
7 hours ago
$begingroup$
Do you see a case for the parentheses for readability?
$endgroup$
– dfhwze
8 hours ago
$begingroup$
Do you see a case for the parentheses for readability?
$endgroup$
– dfhwze
8 hours ago
1
1
$begingroup$
Parentheses can enhance readability if the expression mixes different types of operators like shift operators, arithmetic operators and others, where the operator precedence might not be obvious at a first glance, since C# has a lot of levels of precedence. In this specific case, I don’t see any advantage for parentheses.
$endgroup$
– Olivier Jacot-Descombes
7 hours ago
$begingroup$
Parentheses can enhance readability if the expression mixes different types of operators like shift operators, arithmetic operators and others, where the operator precedence might not be obvious at a first glance, since C# has a lot of levels of precedence. In this specific case, I don’t see any advantage for parentheses.
$endgroup$
– Olivier Jacot-Descombes
7 hours ago
1
1
$begingroup$
I do see advantage in parenthesses. You don't have to remember the operator precedence and any differences between languagues. You just set them the way you want them to work and you're done. No need to study the docs. cc @dfhwze :P
$endgroup$
– t3chb0t
7 hours ago
$begingroup$
I do see advantage in parenthesses. You don't have to remember the operator precedence and any differences between languagues. You just set them the way you want them to work and you're done. No need to study the docs. cc @dfhwze :P
$endgroup$
– t3chb0t
7 hours ago
1
1
$begingroup$
@t3chb0t I've had several discussions about the use of parentheses. And in the end we could argue that: (raganwald.com/2016/03/17/…).
$endgroup$
– dfhwze
7 hours ago
$begingroup$
@t3chb0t I've had several discussions about the use of parentheses. And in the end we could argue that: (raganwald.com/2016/03/17/…).
$endgroup$
– dfhwze
7 hours ago
add a comment |
$begingroup$
Make it an enumerator You can make the evaluation lazy and get rid of the intermediate list by changing the return type to IEnumerable<>.
Use named tuples You can make the API more user-friendly by using named tuples. Something like a readonly struct Point would be preferable but if you don't have it or don't want it then named tuples are your best friend.
Interpolation The point generation you're doing is called interpolation. You can use this word in the method name like InterpolateMovement. I don't know if these calculations have any concrete name, but if they have than you may use an even more exact name like InterpolateMovementByAlgorithmName.
Here's an example of how this could look like after implementing the above suggesions:
public IEnumerable<(double X, double Y)> InterpolateMovement(double x1, double y1, double x2, double y2, double divider)
// If points are same, return empty list
if (x1 == x2 && y1 == y2)
yield break; // break the enumeration
// ..
// increment temp vars by difference-division parts
for (int i = 0; i < divider; i++)
xf += xi;
yf += yi;
yield return (xf, yf); // <-- return tuples
$endgroup$
3
$begingroup$
Linear interpolation
$endgroup$
– Henrik Hansen
8 hours ago
add a comment |
$begingroup$
Make it an enumerator You can make the evaluation lazy and get rid of the intermediate list by changing the return type to IEnumerable<>.
Use named tuples You can make the API more user-friendly by using named tuples. Something like a readonly struct Point would be preferable but if you don't have it or don't want it then named tuples are your best friend.
Interpolation The point generation you're doing is called interpolation. You can use this word in the method name like InterpolateMovement. I don't know if these calculations have any concrete name, but if they have than you may use an even more exact name like InterpolateMovementByAlgorithmName.
Here's an example of how this could look like after implementing the above suggesions:
public IEnumerable<(double X, double Y)> InterpolateMovement(double x1, double y1, double x2, double y2, double divider)
// If points are same, return empty list
if (x1 == x2 && y1 == y2)
yield break; // break the enumeration
// ..
// increment temp vars by difference-division parts
for (int i = 0; i < divider; i++)
xf += xi;
yf += yi;
yield return (xf, yf); // <-- return tuples
$endgroup$
3
$begingroup$
Linear interpolation
$endgroup$
– Henrik Hansen
8 hours ago
add a comment |
$begingroup$
Make it an enumerator You can make the evaluation lazy and get rid of the intermediate list by changing the return type to IEnumerable<>.
Use named tuples You can make the API more user-friendly by using named tuples. Something like a readonly struct Point would be preferable but if you don't have it or don't want it then named tuples are your best friend.
Interpolation The point generation you're doing is called interpolation. You can use this word in the method name like InterpolateMovement. I don't know if these calculations have any concrete name, but if they have than you may use an even more exact name like InterpolateMovementByAlgorithmName.
Here's an example of how this could look like after implementing the above suggesions:
public IEnumerable<(double X, double Y)> InterpolateMovement(double x1, double y1, double x2, double y2, double divider)
// If points are same, return empty list
if (x1 == x2 && y1 == y2)
yield break; // break the enumeration
// ..
// increment temp vars by difference-division parts
for (int i = 0; i < divider; i++)
xf += xi;
yf += yi;
yield return (xf, yf); // <-- return tuples
$endgroup$
Make it an enumerator You can make the evaluation lazy and get rid of the intermediate list by changing the return type to IEnumerable<>.
Use named tuples You can make the API more user-friendly by using named tuples. Something like a readonly struct Point would be preferable but if you don't have it or don't want it then named tuples are your best friend.
Interpolation The point generation you're doing is called interpolation. You can use this word in the method name like InterpolateMovement. I don't know if these calculations have any concrete name, but if they have than you may use an even more exact name like InterpolateMovementByAlgorithmName.
Here's an example of how this could look like after implementing the above suggesions:
public IEnumerable<(double X, double Y)> InterpolateMovement(double x1, double y1, double x2, double y2, double divider)
// If points are same, return empty list
if (x1 == x2 && y1 == y2)
yield break; // break the enumeration
// ..
// increment temp vars by difference-division parts
for (int i = 0; i < divider; i++)
xf += xi;
yf += yi;
yield return (xf, yf); // <-- return tuples
edited 8 hours ago
dfhwze
10.8k2 gold badges19 silver badges71 bronze badges
10.8k2 gold badges19 silver badges71 bronze badges
answered 8 hours ago
t3chb0tt3chb0t
38.3k7 gold badges61 silver badges142 bronze badges
38.3k7 gold badges61 silver badges142 bronze badges
3
$begingroup$
Linear interpolation
$endgroup$
– Henrik Hansen
8 hours ago
add a comment |
3
$begingroup$
Linear interpolation
$endgroup$
– Henrik Hansen
8 hours ago
3
3
$begingroup$
Linear interpolation
$endgroup$
– Henrik Hansen
8 hours ago
$begingroup$
Linear interpolation
$endgroup$
– Henrik Hansen
8 hours ago
add a comment |
$begingroup$
The parameter name divider doesn't say much. I think I would call it numPoints or countOfPoints or numOffsets.
List<Tuple<double, double>> points = new List<Tuple<double, double>>();
You know the size of the list, so to improve performance you can set the capacity of the list
List<Tuple<double, double>> points = new List<Tuple<double, double>>(divider);
double xi = (x2 - x1);
double yi = (y2 - y1);
// divide difference into n parts
xi = xi / divider;
yi = yi / divider;
can be done more elegantly:
double xi = (x2 - x1) / divider;
double yi = (y2 - y1) / divider;
$endgroup$
add a comment |
$begingroup$
The parameter name divider doesn't say much. I think I would call it numPoints or countOfPoints or numOffsets.
List<Tuple<double, double>> points = new List<Tuple<double, double>>();
You know the size of the list, so to improve performance you can set the capacity of the list
List<Tuple<double, double>> points = new List<Tuple<double, double>>(divider);
double xi = (x2 - x1);
double yi = (y2 - y1);
// divide difference into n parts
xi = xi / divider;
yi = yi / divider;
can be done more elegantly:
double xi = (x2 - x1) / divider;
double yi = (y2 - y1) / divider;
$endgroup$
add a comment |
$begingroup$
The parameter name divider doesn't say much. I think I would call it numPoints or countOfPoints or numOffsets.
List<Tuple<double, double>> points = new List<Tuple<double, double>>();
You know the size of the list, so to improve performance you can set the capacity of the list
List<Tuple<double, double>> points = new List<Tuple<double, double>>(divider);
double xi = (x2 - x1);
double yi = (y2 - y1);
// divide difference into n parts
xi = xi / divider;
yi = yi / divider;
can be done more elegantly:
double xi = (x2 - x1) / divider;
double yi = (y2 - y1) / divider;
$endgroup$
The parameter name divider doesn't say much. I think I would call it numPoints or countOfPoints or numOffsets.
List<Tuple<double, double>> points = new List<Tuple<double, double>>();
You know the size of the list, so to improve performance you can set the capacity of the list
List<Tuple<double, double>> points = new List<Tuple<double, double>>(divider);
double xi = (x2 - x1);
double yi = (y2 - y1);
// divide difference into n parts
xi = xi / divider;
yi = yi / divider;
can be done more elegantly:
double xi = (x2 - x1) / divider;
double yi = (y2 - y1) / divider;
answered 8 hours ago
Henrik HansenHenrik Hansen
12k1 gold badge16 silver badges41 bronze badges
12k1 gold badge16 silver badges41 bronze badges
add a comment |
add a comment |
$begingroup$
Dividor
dividor is ill-defined. It acts as a factor for quantization:
xi = xi / divider;
But also as threshold for yielding smoothed results:
for (int i = 0; i < divider; i++)
While this seems fine if dividor is $integer >= 2$, it could yield unwanted results for fractions (as it is a double precision integer). I would at least change its type to int or uint instead and add an out-of-bound guard. If you would decide to allow fractions, make it clear in the spec how the edge case near the end is handled, since you might get a scenario where you don't synchronize with the end value.
Usability
GeneratePointsForSmoothMovement is a low level generator. The caller code should still think about technical parameters to provide. And if a caller requires several levels of smoothness, multiple calls with different parameters have to be executed. In order to provide the consumer a solution that avoids most overhead, you could write an extension method on IEnumerable<Tuple<Double,Double>> and preferrably also on IDictionary<Double,Double> for faster lookup.
In pseudo code:
public static Fun<Double, Double> ToContinuousFunction(
this IDictionary<Double,Double> points)
return new Function<Double, Double>(x =>
if (points.TryGetValue(x, out var y))
return y;
// .. perform lineair interpolation or extrapolation based on nearby points
);
Let's say we have points (x: 1, y: 10) and (x: 2, y: 20):
var f = points.ToContiniousFunction();
var yValues = new []
f(1) // 10 (from cache)
,f(1.5) // 15 (interpolation)
,f(2) // 20 (from cache)
,f(3) // 30 (extrapolation)
;
$endgroup$
$begingroup$
Very acute observation.
$endgroup$
– Henrik Hansen
6 hours ago
1
$begingroup$
@HenrikHansen there is actually a very nice pattern you can make here by wrapping a dictionary of (double,double) in a function that performs inter- and extrapolation when a requested value is not cached in the dic. this way you could do var f = pointsDic.ToFunction(); var x = 1.16f; var y = f(x); etc without having to worry whether x is observed in the dictionary.
$endgroup$
– dfhwze
6 hours ago
add a comment |
$begingroup$
Dividor
dividor is ill-defined. It acts as a factor for quantization:
xi = xi / divider;
But also as threshold for yielding smoothed results:
for (int i = 0; i < divider; i++)
While this seems fine if dividor is $integer >= 2$, it could yield unwanted results for fractions (as it is a double precision integer). I would at least change its type to int or uint instead and add an out-of-bound guard. If you would decide to allow fractions, make it clear in the spec how the edge case near the end is handled, since you might get a scenario where you don't synchronize with the end value.
Usability
GeneratePointsForSmoothMovement is a low level generator. The caller code should still think about technical parameters to provide. And if a caller requires several levels of smoothness, multiple calls with different parameters have to be executed. In order to provide the consumer a solution that avoids most overhead, you could write an extension method on IEnumerable<Tuple<Double,Double>> and preferrably also on IDictionary<Double,Double> for faster lookup.
In pseudo code:
public static Fun<Double, Double> ToContinuousFunction(
this IDictionary<Double,Double> points)
return new Function<Double, Double>(x =>
if (points.TryGetValue(x, out var y))
return y;
// .. perform lineair interpolation or extrapolation based on nearby points
);
Let's say we have points (x: 1, y: 10) and (x: 2, y: 20):
var f = points.ToContiniousFunction();
var yValues = new []
f(1) // 10 (from cache)
,f(1.5) // 15 (interpolation)
,f(2) // 20 (from cache)
,f(3) // 30 (extrapolation)
;
$endgroup$
$begingroup$
Very acute observation.
$endgroup$
– Henrik Hansen
6 hours ago
1
$begingroup$
@HenrikHansen there is actually a very nice pattern you can make here by wrapping a dictionary of (double,double) in a function that performs inter- and extrapolation when a requested value is not cached in the dic. this way you could do var f = pointsDic.ToFunction(); var x = 1.16f; var y = f(x); etc without having to worry whether x is observed in the dictionary.
$endgroup$
– dfhwze
6 hours ago
add a comment |
$begingroup$
Dividor
dividor is ill-defined. It acts as a factor for quantization:
xi = xi / divider;
But also as threshold for yielding smoothed results:
for (int i = 0; i < divider; i++)
While this seems fine if dividor is $integer >= 2$, it could yield unwanted results for fractions (as it is a double precision integer). I would at least change its type to int or uint instead and add an out-of-bound guard. If you would decide to allow fractions, make it clear in the spec how the edge case near the end is handled, since you might get a scenario where you don't synchronize with the end value.
Usability
GeneratePointsForSmoothMovement is a low level generator. The caller code should still think about technical parameters to provide. And if a caller requires several levels of smoothness, multiple calls with different parameters have to be executed. In order to provide the consumer a solution that avoids most overhead, you could write an extension method on IEnumerable<Tuple<Double,Double>> and preferrably also on IDictionary<Double,Double> for faster lookup.
In pseudo code:
public static Fun<Double, Double> ToContinuousFunction(
this IDictionary<Double,Double> points)
return new Function<Double, Double>(x =>
if (points.TryGetValue(x, out var y))
return y;
// .. perform lineair interpolation or extrapolation based on nearby points
);
Let's say we have points (x: 1, y: 10) and (x: 2, y: 20):
var f = points.ToContiniousFunction();
var yValues = new []
f(1) // 10 (from cache)
,f(1.5) // 15 (interpolation)
,f(2) // 20 (from cache)
,f(3) // 30 (extrapolation)
;
$endgroup$
Dividor
dividor is ill-defined. It acts as a factor for quantization:
xi = xi / divider;
But also as threshold for yielding smoothed results:
for (int i = 0; i < divider; i++)
While this seems fine if dividor is $integer >= 2$, it could yield unwanted results for fractions (as it is a double precision integer). I would at least change its type to int or uint instead and add an out-of-bound guard. If you would decide to allow fractions, make it clear in the spec how the edge case near the end is handled, since you might get a scenario where you don't synchronize with the end value.
Usability
GeneratePointsForSmoothMovement is a low level generator. The caller code should still think about technical parameters to provide. And if a caller requires several levels of smoothness, multiple calls with different parameters have to be executed. In order to provide the consumer a solution that avoids most overhead, you could write an extension method on IEnumerable<Tuple<Double,Double>> and preferrably also on IDictionary<Double,Double> for faster lookup.
In pseudo code:
public static Fun<Double, Double> ToContinuousFunction(
this IDictionary<Double,Double> points)
return new Function<Double, Double>(x =>
if (points.TryGetValue(x, out var y))
return y;
// .. perform lineair interpolation or extrapolation based on nearby points
);
Let's say we have points (x: 1, y: 10) and (x: 2, y: 20):
var f = points.ToContiniousFunction();
var yValues = new []
f(1) // 10 (from cache)
,f(1.5) // 15 (interpolation)
,f(2) // 20 (from cache)
,f(3) // 30 (extrapolation)
;
edited 3 hours ago
answered 6 hours ago
dfhwzedfhwze
10.8k2 gold badges19 silver badges71 bronze badges
10.8k2 gold badges19 silver badges71 bronze badges
$begingroup$
Very acute observation.
$endgroup$
– Henrik Hansen
6 hours ago
1
$begingroup$
@HenrikHansen there is actually a very nice pattern you can make here by wrapping a dictionary of (double,double) in a function that performs inter- and extrapolation when a requested value is not cached in the dic. this way you could do var f = pointsDic.ToFunction(); var x = 1.16f; var y = f(x); etc without having to worry whether x is observed in the dictionary.
$endgroup$
– dfhwze
6 hours ago
add a comment |
$begingroup$
Very acute observation.
$endgroup$
– Henrik Hansen
6 hours ago
1
$begingroup$
@HenrikHansen there is actually a very nice pattern you can make here by wrapping a dictionary of (double,double) in a function that performs inter- and extrapolation when a requested value is not cached in the dic. this way you could do var f = pointsDic.ToFunction(); var x = 1.16f; var y = f(x); etc without having to worry whether x is observed in the dictionary.
$endgroup$
– dfhwze
6 hours ago
$begingroup$
Very acute observation.
$endgroup$
– Henrik Hansen
6 hours ago
$begingroup$
Very acute observation.
$endgroup$
– Henrik Hansen
6 hours ago
1
1
$begingroup$
@HenrikHansen there is actually a very nice pattern you can make here by wrapping a dictionary of (double,double) in a function that performs inter- and extrapolation when a requested value is not cached in the dic. this way you could do var f = pointsDic.ToFunction(); var x = 1.16f; var y = f(x); etc without having to worry whether x is observed in the dictionary.
$endgroup$
– dfhwze
6 hours ago
$begingroup$
@HenrikHansen there is actually a very nice pattern you can make here by wrapping a dictionary of (double,double) in a function that performs inter- and extrapolation when a requested value is not cached in the dic. this way you could do var f = pointsDic.ToFunction(); var x = 1.16f; var y = f(x); etc without having to worry whether x is observed in the dictionary.
$endgroup$
– dfhwze
6 hours ago
add a comment |
Waleed is a new contributor. Be nice, and check out our Code of Conduct.
Waleed is a new contributor. Be nice, and check out our Code of Conduct.
Waleed is a new contributor. Be nice, and check out our Code of Conduct.
Waleed is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f227404%2fgenerate-points-for-smooth-movement-between-two-given-points%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
$begingroup$
What is your question?
$endgroup$
– Olivier Jacot-Descombes
9 hours ago
$begingroup$
@OlivierJacot-Descombes this website is for code review and improvements suggestion right?
$endgroup$
– Waleed
8 hours ago
2
$begingroup$
Are you questioning the interpolation method, the code quality, memory or time efficiency, correctness or something, else?
$endgroup$
– Olivier Jacot-Descombes
8 hours ago