I am creating three angles. These angles creates a triangle.I want to show calculated angle in my canvas, for that I am calculating angle and rounding off for showing.While calculating the angle's , I am rounding off the decimal digits using Math.round().
So if I got 65.25, 70.36, 44.39 degree as value of three angles and after rounding off it will be 65,70,44,which become 179 degree instead of 180 degree(One degree is missing here).How can I solve this problem ?
Here are some images for reference
One approach is to compute the third angle (rounded) based upon the other two, rather than simply rounding them all as you have done. For instance:
var th0 = 65.25;
var th1 = 70.36;
var th2 = 44.39;
var th0r = Math.round(th0);
var th1r = Math.round(th1);
var th2r = 180.0 - th0r - th1r;
This will force th0r + th1r + th2r to always sum to 180. You can become a little more sophisticated by picking the best angle to compute from the other two, but this will probably suffice for most applications.
Related
I'm using this equation to calculate a series of points along a quadratic curve:
// Returns a point on a quadratic bezier curve with Robert Penner's optimization of the standard equation
result.x = sx + t * (2 * (1 - t) * (cx - sx) + t * (ex - sx));
result.y = sy + t * (2 * (1 - t) * (cy - sy) + t * (ey - sy));
Sadly the points are unevenly distributed, as you can see in the dashed-line rendering below. The points are denser in the middle of the curve, and are further spaced apart near the edges. How can I calculate a evenly distributed set of points along a quadratic bezier curve?
Please note that I'm using this for rendering a dashed line, so a slow solution in MATLAB or something will not do. I need a fast solution that will fit inside a renderer. This is not for research or a one-off calculation!
Edit: I'm not asking how to accomplish the above. The above is MY RENDERING! I already know how to estimate the length of a bezier, calculate the number of points, etc, etc. What I need is a better bezier point interpolation algorithm since the one I have calculates points unevenly distributed along the curve!
You want to generate equidistant (by arc length) subdivision of quadratic Bezier curves.
So you need subdivision procedure and function for calculation of curve length.
Find length of the whole curve (L), estimate desired number of segments (N), then generate subdivision points, adjusting t parameters to get Bezier segments with length about L/N
Example: you find L=100 and want N=4 segments. Get t=1/2, subdivide curve by two parts and get length of the first part. If length > 50, diminish t and subdivide curve again. Repeat (use binary search) until length value becomes near 50. Remember t value and do the same procedure to get segments with length=25 for the first and for the second halves of the curve.
This approach uses the THREE.js library, which is not in the OP's question, but may be useful if only to look at how they approach it:
var curve = new THREE.QuadraticBezierCurve(
new THREE.Vector2( -10, 0 ),
new THREE.Vector2( 20, 15 ),
new THREE.Vector2( 10, 0 )
);
var points = curve.getSpacedPoints(numPoints);
I would like to calculate the distance between two degree values. I know that I could use this if the points just where on one axis:
var dist = Math.abs( x1 - x2 );
...but the problem with degrees is, that they can either be negative or positive, also they could be somewhere above 360. My goal is to calculate the distance, no matter if the rotation is negative or higher then 360°
EDIT
To make it clearer what I want: For example, I could could have the values -90deg and 270deg. This should result in a result of 0 for the distance. If the first element's rotation would change to either -100deg of -80deg, the distance should change to 10.
If you want this to work for any angle (including angles like 750 deg) and in a language where you have a remainder operator that's signed (like Java or JavaScript), then you need to do more work. If you're in a language with an unsigned operator, then the answer by Rory Daulton is good. (That is, in summary, use rot1%360 below where I call modulo(rot1,360) and similarly for rot2.)
First you need to make each negative angle into an equivalent positive angle. There's no single operator that will do this since, for example, -10 % 360 = -10 in these languages. You can get this with a function like this (assuming y is positive):
function modulo(x,y) {
var xPrime = x;
while(xPrime<0) {
xPrime += y; // ASSUMES y > 0
}
return xPrime % y;
}
Then you can do more or less as suggested by others, but using this custom function instead of the % operator.
var distance = Math.abs(modulo(rot1,360) - modulo(rot2,360))
distance = Math.min(distance, 360-distance)
Python code that seems to work in all cases is
dist = abs(x1 % 360 - x2 % 360)
dist = min(dist, 360 - dist)
That last line is needed to handle a case like x1=10; x2=350. The other answers would give 340 but the proper answer is 20.
Old topic but, the accepted answer is not really acceptable for a problem I had myself because of the while loop, and sadly that is the best I could find on a google search. However I found a better and faster solution if you might as well have to deal with very high negative rotation values.
This line of code takes a rotation value (r) and maps it to a range of 0-360.
r = (r<0) ? (r+(Math.ceil(-r/360)*360)) : (r%360);
Further explanation:
The accepted answer adds 360 every loop to the negative rotation value until it is positive, whereas my solution calculates how often it needs to add 360 and does that in one go.
So, I worked it out, following this answer:
function modulo(value, mod) {
return value - Math.floor( value/mod ) * value;
}
var dist = rotation1 - rotation2;
dist = Math.abs( modulo( (dist + 180), 360 ) - 180 );
EDIT
Actually, this answer works as well. Ported to JavaScript it would be:
var dist = Math.abs(rotation1 % 360 - rotation2 % 360);
dist = Math.min(dist, 360 - dist);
I like it, because it doesn't need the special modulo function.
This calculates vertex coordinates on ellipse:
function calculateEllipse(a, b, angle)
{
var alpha = angle * (Math.PI / 180) ;
var sinalpha = Math.sin(alpha);
var cosalpha = Math.cos(alpha);
var X = a * cosalpha - b * sinalpha;
var Y = a * cosalpha + b * sinalpha;
}
But how can I calculate the "angle" to get equal or roughly equal circumference segments?
So from what Jozi's said in the OP's comments, what's needed isn't how to subdivide an ellipse into equal segments (which would require a whole bunch of horrible integrals), it's to construct an ellipse from line segments of roughly equal length.
There are a whole pile of ways to do that, but I think the best suited for the OP's purposes would be the concentric circle method, listed on the page as 'the draftman's method'. If you don't mind installing the Mathematica player, there's a neat lil' app here which illustrates it interactively.
The problem with those methods is that the segment lengths are only roughly equal at low eccentricities. If you're dealing in extreme eccentricities, things get a lot more complicated. The simplest solution I can think of is to linearly approximate the length of a line segment within each quadrant, and then solve for the positions of the endpoints in that quadrant exactly.
In detail: this is an ellipse quadrant with parameters a = 5, b = 1:
And this is a plot of the length of the arc subtended by an infinitesimal change in the angle, at each angle:
The x axis is the angle, in radians, and the y axis is the length of the arc that would be subtended by a change in angle of 1 radian. The formula, which can be derived using the equations in the Wikipedia article I just linked, is y = Sqrt(a^2 Sin^2(x) + b^2 Cos^2(x)). The important thing to note though is that the integral of this function - the area under this curve - is the length of the arc in the whole quadrant.
Now, we can approximate it by a straight line:
which has gradient m = (a-b) / (Pi/2) and y intercept c = b. Using simple geometry, we can deduce that the area under the red curve is A = (a+b)*Pi/4.
Using this knowledge, and the knowledge that the area under the curve is the total length of the curve, the problem of constructing an approximation to the ellipse reduces to finding say a midpoint-rule quadrature (other quadratures would work too, but this is the simplest) of the red line such that each rectangle has equal area.
Converting that sentence to an equation, and representing the position of a rectangle in a quadrature by it's left hand boundary x and its width w, we get that:
(v*m)*w^2 + (m*x+c)*w - A/k == 0
where k is the number of pieces we want to use to approximate the quadrant, and v is a weighting function I'll come to shortly. This can be used to construct the quadrature by first setting x0 = 0 and solving for w0, which is then used to set x1 = w0 and solve for w1. Then set x2 = w1, etc etc until you've got all k left-hand boundary points. The k+1th boundary point is obviously Pi/2.
The weighting function v effectively represents where the rectangle crosses the red line. A constant v = 0.5 is equivalent to it crossing in the middle, and gets you this with 10 points:
but you can play around with it to see what better balances the points. Ideally it should stay in the range [0, 1] and the sum of the values you use should be k/2.
If you want an even better approximation without messing around with weighting functions, you could try least-squares fitting a line rather than just fitting it to the endpoints, or you could try fitting a cubic polynomial to the blue curve instead of a linear polynomial. It'll entail solving quartics but if you've a maths package on hand that shouldn't be a problem.
Too long for a comment, so I suppose this has to be an answer ...
Here's a mathematically simple approach to forming a first order approximation. Pick one quadrant. You can generate the data for the other quadrants by reflection in the X and Y axis. Calculate (x,y) for the angle = 0 degrees, 1 degree, ... 90 degrees. Now you want the little lengths joining consecutive points. If (x_n, y_n) are the coordinates at angle = n, then Pythagoras tells us the distance D between points (x_n, y_n) and (x_n+1, y_n+1) is D = sqrt((x_n+1 - x_n)^2 + (y_n+1 - y_n)^2). Use this formula to produce a table of cumulative distances around the ellipse for angles from 0 degrees to 90 degrees. This is the inverse of the function you seek. Of course, you don't have to pick a stepsize of 1 degree; you could use any angle which exactly divides 90 degrees.
If you want to find the angle which corresponds to a perimeter step size of x, find the largest angle n in your table producing a partial perimeter less than or equal to x. The partial perimeter of angle n+1 will be larger than x. Use linear interpolation to find the fractional angle which corresponds to x.
All we are doing is approximating the ellipse with straight line segments and using them instead of the original curve; its a first order approximation. You could do somewhat better by using Simpson's rule or similar instead of linear interpolation.
Yes, you have to calculate the table in advance. But once you have the table, the calculations are easy. If you don't need too much accuracy, this is pretty simple both mathematically and coding-wise.
Hey i've made a rotation function in Javascript for rotating some 2D vector(point).
The Y output of the function works as expected, however the X value is outputting some crazy number, can anyone point out the floor in my logic?
Vector2.prototype.rotate = function(degrees){
var angle = degrees * TO_RADIANS; //Convert to radians.
var x = (this.getX() * Math.cos(angle)) - (this.getY() * Math.sin(angle));
var y = (this.getX() * Math.sin(angle)) + (this.getY() * Math.cos(angle));
return new Vector2(x,y);
};
Inputting Vector(1,0) into this function with a rotation of 90 degrees outputs 6.someDecimalPlaces e-17; which is obviously incorrect.
The outputted Y value however works as expected and returns 1.
Thanks in advance
The "6.someDecimalPlaces e-17" you're seeing is due to Javascript's handling of floating point numbers. What you're seeing is a rounding error in converting back from binary floating point to decimal. There's no easy fix for this although there are libraries that attempt to overcome the problem.
If you want rounded numbers for pixel perfect CSS manupilation you're best bet is to round the numbers coming out of this function or cast them to integer.
To calculated the value of the derivative of a given function Func at a given point x, to get a good precision one would think this:
a = Fun( x - Number.MIN_VALUE)
b = Func( x + Number.MIN_VALUE)
return (b-a)/(2*Number.MIN_VALUE)
Now for any x + Number.MIN_VALUE (or x - Number.MIN_VALUE) both return x in javascript.
I tried of different values, and 1 + 1e-15 returns 1.000000000000001. Trying to get more precision, 1 + 1e-16 returns 1. So I'll have to use 1e-15 instead of Number.MIN_VALUE which is 5e-324.
Is there a way to get a better precision in this case in javascript?
This is not at all about javascript, actually.
Reducing the separation between the points will not increase your precision of the derivative. The values of the function in the close points will be computed with some error in the last digits, and finally, your error will be much larger than the point separation. Then you divide very small difference which has a huge relative error by a very small number, and you most likely get complete rubbish.
The best way to get a better value of the derivative is to calculate function in multiple points (with not very small separation) and then construct an approximation polynomial and differentiate it in the point of your interest.