I am having trouble understanding a function hopefully someone can help me out here. I am trying to find the pitch diameter of a sprocket the function for this in JavaScript is:
function sprocket_diam(dataform,pitch,teeth)
{
var a,b,c,d,e;
a = pitch / 2;
b = teeth * 2;
c = 360 / b;
d = Math.sin ((c * Math.PI) / 180);
e = (a / d) * 2
dataform.diam.value = e;
}
The above function works just as intended but I am trying to do this by hand on a calculator. I think the problem I am having comes in the d variable. For example lets say I have a 15 tooth sprocket with a pitch of .5". Using the above formula the numbers for the variables I get are:
a=0.25,b=30,c=12, and for d I take (12*3.14)/180 which gives me 0.2093 so e=(0.25/.2093)*2 which ends up being 2.388915432 but is the incorrect answer it should be 2.404867172372066 Can someone point out what I am doing wrong? I have always struggled with math.
You didn't compute the sinus. (Math.sin)
Your error is that you do as if Math.PI would be 3.14.
If you use the precise value of Math.PI, you get 12*Math.PI/180 == 0.20943951023931953 instead of the 0.2093 you use and at the end you find 2.404867172372066
Related
I'm trying to calculate the volume of a sphere, with floating points, but I couldn't quite understand the logic behind the exercise.
Write a program that calculates and displays the volume of a sphere,
providing the value of its radius (R). The formula for calculating
volume is: (4/3) * pi * R3. Consider (assign) to pi the value 3.14159.
const PI = 3.14159;
let R = parseFloat(gets());
//TODO: Fill in the blanks with a possible solution to the challenge
print("VOLUME = " + );
You should try by yourself, but here is the solution and explanation.
If you are using javascript on the browser:
let radius = parseFloat(prompt("Enter value for radius: "));
let volume = 4/3 * Math.PI * Math.pow(radius, 3);
console.log("The volume is: ", volume);
We are requesting the user input with prompt() and assigning it to radius variable. We calculate the volume with the equation v = 4/3 πr³, Math.PI represents the number PI and Math.pow() calculates the given base (this case, radius) taken to the power of the given exponent. Last step is to print the result to the output, which is done with console.log()
Reading a lot of the tips here, I solved it, I don't know if it's the best way, but I solved it.
const PI = 3.14159;
let R = parseFloat(gets());
var raio = parseFloat(R);
var volumeEsfera = (4/3) * PI * Math.pow(raio, 3);
print("VOLUME = " + volumeEsfera.toFixed(3) );
I reached out for help recently on math.stackexchange.com with a question about 2 dimensional algebra. The answer was promptly provided but it's in mathematical notation unfamiliar to me and the person giving the answer has stopped responding to my questions. While I am extremely grateful to BStar for providing this information, he/she has stopped replying both on the site and the chat, and doesn't seem interested in helping me understand it to the point that I could write programming code to calculate the desired point P. I respect that, but it leaves me stuck for now. Could someone help me convert this sequence of steps into a programming language such as Javascript? (I am actually working in PHP, but Javascript would be more convenient to represent in a runnable Snippet on stackoverflow .. I'm happy with any current language that I can translate into PHP).
The post is at https://math.stackexchange.com/questions/4110517/trig-101-calculate-coords-of-point-p-such-that-it-is-distance-n-from-line-ab-an/4110550?noredirect=1#comment8504010_4110550
The answer given is in Latex but here's a screenshot of it:
The latest description of the process by the author BStar: "Here is the process: First calculate cos B and use arccos to get B. Second calculate tanθ to get θ with arctan by using |BP| is the same from two triangles. Knowing these, we can get vectors BA’ and B’P, thus vectors OA and OP. We get θ to grt vector BA’ in this case, not the other way around. "
I can follow up until step (5) where the comma notation comes in, i.e. k = (-xb, -yb)(xc - xb, yc - yb) / ac. This seems to make k a two dimensional vector but I don't think I ever worked with this notation. Later, k is used in step (6) and (6a) to calculate theta, appearing both in the numerator and denominator of a fraction. I have no idea how to expand this to get an actual value for theta.
(Edit Note: The author BStar assumed point A is at the origin, so (xa, ya) = (0, 0) but I cannot make that assumption in the real world. Thus the vector BA in Step 1 is actually (xa - xb, ya - yb) and his formula for k shown above is actually k = (xa - xb, ya - yb)(xc - xb, yc - yb) / ac. This expansion needs to be carried through the calculation but it's not a major change.)
If we were to frame this in Javascript, I could lay out a framework of what is known at the beginning of the calculation. It's not productive to represent every single step of the mathematical proof given by BStar, but I'm not sure exactly what steps can be left as processes in the mathematical proof and what steps need expounding in code.
/* Known points - A, B, C */
var xa = 10, ya = 10;
var xb = 100, yb = 500;
var xc = 700, yc = 400;
/* Known lengths m and n (distance perpendicularly from AB and AC) */
var m = 30;
var n = 50;
/* Point we want to calculate, P */
var px = 0, py = 0;
/* Calculation goes here - some Javascript notes:
* var a = Math.sin(angInRadians);
* var b = Math.asin(opposite / hypotenuse);
* var c = Math.pow(number, 2); // square a number
* var d = Math.sqrt(number);
*/
/* Print the result */
console.log('Result: P (' + px + ', ' + py + ')');
How would one express the maths from the diagram in the programming snippet above?
I think I can get you to the angle of B but I'm not very good with math and get lost with all those variables. If you are stuck at figuring out the angle try this and see if it does what you want. It seems to do what step 5 is asking but double check my work.
let pointA = {x: 100, y: 0};
let pointB = {x: 20, y: 20};
let pointC = {x: 0, y: 100};
let distBA_x = pointB.x - pointA.x;
let distBA_y = pointB.y - pointA.y;
//let BA_a = Math.sqrt(distBA_x*distBA_x + distBA_y*distBA_y);
let distBC_x = pointB.x - pointC.x;
let distBC_y = pointB.y - pointC.y;
//let BC_c = Math.sqrt(distBC_x*distBC_x + distBC_y*distBC_y);
var angle = Math.atan2(distBA_x * distBC_y - distBA_y * distBC_x, distBA_x * distBC_x + distBA_y * distBC_y);
if(angle < 0) {angle = angle * -1;}
var degree_angle = angle * (180 / Math.PI);
console.log(degree_angle)
I've laid it out on a canvas so you can see it visually and change the parameters. Hope it helps. Here's the Codepen https://codepen.io/jfirestorm44/pen/RwKdpRw
BA • BC is a "dot product" between two vectors. The result is a single number: It's the sum of the products of vector components. If the vectors are (x1,y1) and (x2,y2) the dot product is x1x2+y1y2.
Assuming you don't have a library for vector calculations and don't want to create one, the code for computing k would be:
k = (-xb*(xc - xb)-yb*(yc - yb)) / ac
I am trying to "alter" the sin cos and tan function from Math object so it can accept recognize if it is a degree "d" or radians. I have an idea on how to do it but I do not know to do it without changing my main function
(function() {
var angle;
while (angle = parseFloat(readline())) {
print(Math.sin(angle, "d").toPrecision(5)); // degrees
print(Math.sin(angle).toPrecision(5)); // radians
print(Math.cos(angle, "d").toPrecision(5));
print(Math.cos(angle).toPrecision(5));
print(Math.tan(angle, "d").toPrecision(5));
print(Math.tan(angle).toPrecision(5));
}
})();
How do alter does function so they can accept the "d" argument I tried use Object.create and another things like JSON.parse(JSON.stringify(Math)); but it doesn't work I need to know how to deep copy Math
You can override Math (in a closure) with an object which inherits from Math:
(function(globalMath) {
// Overriding Math:
var Math = Object.create(globalMath);
// Enhancing trigonometric methods:
var trig = ['sin', 'cos', 'tan'];
for(var i=0; i<3; ++i)
Math[trig[i]] = (function(trigFunc){
return function(angle, d) {
if(d==="d") angle *= Math.PI / 180;
return trigFunc(angle);
};
})(globalMath[trig[i]]);
// Now you can use the enhanced methods:
Math.sin(Math.PI/6); // 0.5
Math.sin(30, 'd'); // 0.5
// You can also use original methods:
globalMath.sin(Math.PI/6); // 0.5
globalMath.sin(Math.PI/6, 'd'); // 0.5 ('d' is ignored)
// Math is a shortcut of globalMath for other methods:
Math.max(1,2); // 2
})(Math);
Everything's an Object in JavaScript, so you can re-write the native Math functions. But this is not recommended, as other commentators have said.
It's simpler to create your own function that converts to degrees internally, like this:
function sinDegrees(angle) {
return Math.sin(angle * (Math.PI / 180));
}
It could even be part of the Math object, if you want:
Math.sinDegrees = sinDegrees;
If you still want to modify the Math.sin function like that, then you can do this:
Math._sin = Math.sin; // save a ref. to the old sin
Math.sin = function sin(angle, type) {
if (type == 'd')
return Math._sin(angle * (Math.PI / 180));
else
return Math._sin(angle);
}
The better solution here is to have a toRad function. It looks very similar to your target code without breaking basic good practices (don't modify objects you didn't create).
function toRad(angle){
return angle * (Math.PI / 180);
}
print(Math.sin(toRad(angle)).toPrecision(5)); // degrees
print(Math.sin(angle).toPrecision(5)); // radians
print(Math.cos(toRad(angle)).toPrecision(5));
print(Math.cos(angle).toPrecision(5));
print(Math.tan(toRad(angle)).toPrecision(5));
print(Math.tan(angle).toPrecision(5));
This also saves you from defining custom versions of each function.
I'm thinking of a wheel of fortune type of thing where you have to check if a marker lands on a slot. Visually, we can see 0, 2pi, 4pi, etc... are in the same position. How do I check if 0 is equal to 2pi/4pi programmatically? Assuming I have the radius as well, I thought, maybe I have to convert it to cartesian coordinates first and then compare it. However, is there a better way to do this?
Edit: Also, I should make clear that the mark can land anywhere in between a slot. For example, the marker could be anywhere in between 0 to pi/6.
Is this what you want?
var smallestEquivalentValueInRadians = originalValueInRadians % (2 * Math.PI);
If you want to compare, you can do:
a % (2 * Math.PI) === b % (2 * Math.PI)
% is the modulo operator, basically it subtracts the second operand from the first, as many times as it can (assuming you are dealing with positive numbers).
To cater for negative values:
function normalizeRadian(a) {
var circle = Math.PI * 2;
a = a % circle;
if (a < 0) {
a += circle;
}
return a;
}
Also when comparing floats, it's a good idea to have some "fuzzyness", since opperations on them can be imprecise.
function fuzzyEqual(a, b) {
var fuzz = 0.001;
return a < b + fuzz && a > b - fuzz;
}
So the complete solution is:
function fuzzyEqualRadians(a, b) {
return fuzzyEqual(normalizeRadian(a), normalizeRadian(b));
}
I'm well acquainted with basic math and know the equations, but when I try to implement them in canvas they fail.
Here's the relevant code:
function distance(one,two){
var a, b
if(one[0] > one[1]){
a = one[1] - one[0]
}else{
a = one[0] - one[1]
}
if(two[0] > two[1]){
b = two[1] - two[0]
}else{
b = two[0] - two[1]
}
var c = a^2 + b^2;
return Math.sqrt(c);
}
radius = distance([centerX,e.clientX], [centerY,e.clientY])
context.fillCircle(centerX, centerY, radius, "white");
Here's the code in action
As you can see, the circle is far too short and I don't know why... when I remove the sqrt, it becomes out of whack very quickly.
^ does not do what you think it does.
js> 8^2
10
js> Math.pow(8,2)
64