笛卡儿到极坐标 [英] Cartesian to polar coordinates

查看:243
本文介绍了笛卡儿到极坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看这里的例子:函数来解决这个问题。它是一个接受2个参数( x y 坐标)的函数,因此系统可以将结果添加或减去 产生正确的角度。而不是调用

  Math.atan(y / x)

您只需调用

  Math.atan2(y,x) 


Take a look at the example here: http://www.brianhare.com/physics/so.html

Take a look at console.log where I am using these two main functions:

    function distanceBetween2pts(x1, y1, x2, y2) {
        console.log("Particle: ("+x1+","+y1+") Mouse: ("+x2+","+y2+")");
        //  Pythagoras Theorem
        // PQ = sqrt( (x2-x1)^2 + (y2-y1)^2 )
        var x = (x2-x1);
        var y = (y2-y1);

        this.radius = Math.sqrt(x*x + y*y);
        this.x = x;
        this.y = y;
    }

    function polar2cartesian(R, theta) {
        this.x = R * Math.cos(theta);
        this.y= R * Math.sin(theta);
    }

Where when the mouse is above and to the right of the particle (center circle) such as :

The console log displays:

Particle: (300,250) Mouse: (326,223)
artan(-27 / 26) = angle: -46.08092418666069 - theta -0.8042638494191191

where it should be arctan(27/26) = angle : 46 : theta = 0.8. because even thouse the mouse is "above" the center, it's reading the y2-y1 as -27 because the coord system is based about 0,0 being top left.

The issue then is when both X and Y are negative making theta positive, when it should be pointing the opposite direction (outward from the center point). I know I could just do a 180 degree trick here but I want to understand what im doing wrong.

解决方案

In Javascript and many languages there is an atan2 function to tackle this problem. It is a function which takes 2 arguments (the x and y coordinates), so the system can add or subtract π to the result to produce the correct angle. Instead of calling

Math.atan(y/x)

you just call instead

Math.atan2(y, x)

这篇关于笛卡儿到极坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆