Trouver l'angle entre deux points

13

Étant donné deux points Aet B, trouvez l'angle d'une ligne AOà l'autre BOautour du point Ooù se Otrouve l'origine ( (0,0)). De plus, l'angle peut être positif ou négatif selon la position des points (voir exemples). L'entrée sera des points Aet B, et peut être donnée sous n'importe quelle forme pratique. La sortie sera l'angle en degrés (mais elle est positive si elle AOest tournée dans le sens antihoraire autour de l'origine pour obtenir BOet négative si elle est tournée dans le sens horaire). Si l'angle est de 180 degrés, vous pouvez renvoyer une sortie négative ou positive. De même, l'angle peut être la version positive ou négative du même angle ( 90 degest égal à -270 deg). Exemples:

  • Entrée: A(5,5) B(5,-5)Sortie: -90( AOest tourné -90degrés pour obtenir BO).

  • Entrée: A(5,-5) B(5,5)Sortie: 90( AOest tourné 90degrés pour obtenir BO).

C'est le , donc le code le plus court en octets gagne!

Alien G
la source
11
Quelle précision faut-il?
Reto Koradi du
2
Pouvons-nous prendre l'entrée comme deux nombres complexes?
lirtosiast
5
Quelle devrait être la sortie si un point est (0,0)?
lirtosiast
1
@ThomasKwa Je ne connais pas l'OP, mais je l'ai traité uniquement comme une entrée de nombre entier / décimal, et l'entrée n'aurait jamais de point (0,0).
GamrCorps
2
Astuce: L'angle entre AOet BOserait généralement appelé angle AOB.
ETHproductions du

Réponses:

12

Pyth, 11 octets

.t-FPM.jMQ6

Manifestation

L'entrée est donnée au format:

[[Bx, By], [Ax, Ay]]

Si l'on souhaite que A vienne en premier, cela peut être modifié pour 1 octet.

Explication:

.t-FPM.jMQ6
               Implicit: Q = eval(input())
      .jMQ     Convert input pairs to complex numbers.
    PM         Take their phases (angles in the complex plane).
  -F           Take the difference.
.t        6    Convert to degrees
isaacg
la source
22

TI-BASIC, 13 octets

Pour les calculatrices de la série TI-83 + / 84 +.

Degree
Input Y
min(ΔList(R►Pθ(Ans,∟Y

Pour utiliser ce programme, entrez la liste {x1,x2}via la variable Ans et {y1,y2}à l'invite.

lirtosiast
la source
Une commande TI-BASIC est-elle un seul octet?
corsiKa
Toutes les commandes ici, sauf ΔList(, sont un octet chacune. Cela comprend R►Pθ(.
lirtosiast
+1 juste pour utiliser la programmation de la calculatrice. Me ramène à Trig and Calculus dans mes jours de lycée.
вʀaᴎᴅᴏƞ вєнᴎєƞ
Belle référence! Super cool.
corsiKa
10

CJam, 14 octets

q~::ma:-P/180*

Il s'agit d'un programme complet qui lit l'entrée à [[Ax Ay] [Bx By]]partir de STDIN.

Essayez-le en ligne dans l' interpréteur CJam .

Comment ça fonctionne

q~             e# Read and evaluate all input.
  ::ma         e# Replace each point (x, y) with atan2(x, y).
               e# This returns its angle with the positive y axis, measured clockwise.
      :-       e# Compute the difference of the two resulting angles.
               e# This returns the angle between the points, measured counter-clockwise.
        P/180* e# Divide by Pi and multiply by 180 to convert to degrees.
Dennis
la source
5
Amusant que près de la moitié de ce programme ne fait que convertir des radians en degrés ...
Darrel Hoffman
@DarrelHoffman Je trouve encore plus amusant qu'en Pyth la conversion soit de 3 octets au lieu de 6, donc si le défi permettait de rapporter en radians les langues seraient liées
FryAmTheEggman
5

Minkolang 0.9 , 112 octets

I really want to implement trig functions as built-ins now...but this was fun! (Caveat: this outputs the positive angle difference, not the signed angle difference. Given my limitations, I think that's justified.)

4[n]0c2c*1c3c*+r4[2;1R]r+1R+0g*12$:;$:8[0ci2*3+d1R;0g$:1i1+[i2*1+d1+$:*]*]$+'3.141592654'25*9;$:$:12$:r-66*5**N.

Try it here.

Explanation

Je posterai une explication plus complète si quelqu'un le veut, mais l'essentiel est:

4[n]                                    Take in 4 integers from input
0c2c*1c3c*+                             dot product
r4[2;1R]r+1R+0g*12$:;                   magnitudes of vectors
$:                                      dot product divided by magnitudes (z)
8[0ci2*3+d1R;0g$:1i1+             *]    Taylor series for arccos
                     [i2*1+d1+$:*]      In particular, the coefficient (1/2 * 3/4 * ...)
$+                                      Add them all up!
'3.141592654'25*9;$:$:                  Divide by pi for converting to degrees
12$:r-                                  Subtract from 1/2 - I now have arccos(z)
66*5**                                  Convert to degrees
N.                                      Output as number and stop.
El'endia Starman
la source
Does minkolang support comments? I couldn't find it on the readme.
Conor O'Brien
1
@CᴏɴᴏʀO'Bʀɪᴇɴ: It's just like other 2D languages - comments are whatever isn't reached by the program counter.
El'endia Starman
Oh, okay, then. That makes sense, dunno what I was thinking.
Conor O'Brien
@CᴏɴᴏʀO'Bʀɪᴇɴ: Your explicit use of comments in one of your answers makes me consider implementing similar functionality though. It's a neat idea and wouldn't be terribly hard for me to implement.
El'endia Starman
Thanks! :D Was it the Hello World challenge that you noticed the comments in (FYI the interpreter I have made for Simplex runs in different "modes": string mode and comment mode. It makes it really easy to parse and allows you to ignore signal characters of one mode whilst in the other.)
Conor O'Brien
4

Mathematica, 22 bytes

{-1,1.}.ArcTan@@@#/°&

Example:

In[1]:= {-1,1.}.ArcTan@@@#/°&[{{5,5},{5,-5}}]

Out[1]= -90.

In[2]:= {-1,1.}.ArcTan@@@#/°&[{{5,-5},{5,5}}]

Out[2]= 90.
alephalpha
la source
Will this work for inputs like {{0,1},{1,0}}
lirtosiast
@ThomasKwa Of course it will.
alephalpha
4

Javascript, 66 bytes

let f=(a,b)=>(Math.atan2(b.y,b.x)-Math.atan2(a.y,a.x))*180/Math.PI;

demo

lecoco
la source
23 seconds before me =P Nice golf though! Btw, you can omit the let f=, and it's still considered valid as an anonymous function.
Mwr247
3

Julia, 18 25 bytes

f(A,B)=angle(B/A)/pi*180

This assumes that "any convenient form" already allows for A and B to be given as complex numbers. Then, the complex number arithmetic does all the heavy lifting.

Edit: converted snippet to function. 18 byte version only works in the Julia REPL.

ojdo
la source
3

Python 2.7, 73 Bytes

from math import*
f=lambda A,B:degrees(atan2(B[1],B[0])-atan2(A[1],A[0]))

Test:

f((5,5),(5,-5)) #-90.0
f((5,-5),(5,5)) #90.0
Aetienne Sardon
la source
Welcome to PPCG! This is code-golf, so you should try to remove as many spaces as you can and shorten your code.
mbomb007
1
You can make your code shorter by recklessly adding some *s all over the place
FryAmTheEggman
3

Octave, 43 bytes

f=@(a,b)(cart2pol(b)-cart2pol(a))(1)*180/pi

Input/Output:

octave:40> f([5,5],[5,-5])
ans = -90

octave:41> f([1,0],[0,1])
ans = 90
dcsohl
la source
3

CJam, 15 bytes

l~ma@@ma-P/180*

Thought I'll get in the CJam game as well. Try it online. Input is in form of bx by ax ay. Unfortunately, this is the shortest method of doing this challenge without copying Dennis' answer.

GamrCorps
la source
3

TeaScript, 28 bytes

I really should of implemented trig functions...

$.atan2(_[3]-y,z-x)*180/$.PI

Try it online input is a.x a.y b.x b.y

Explanation

$.atan2(       // Arc Tangent of...
    _[3] - y,  // 4th input - 2nd input
       z - x,  // 3rd input - 1st input
) * 180 / $.PI // Converts rad -> deg
Downgoat
la source
2

Ruby, 64, 58 bytes

a=->(b){b.map{|c|Math.atan2(*c)}.reduce(:-)*180/Math::PI}

Usage

a.call [[5, 5], [5, -5]] # => -90.0
a.call [[5, -5], [5, 5]] # => 90.0
Harsh Gupta
la source
2

JavaScript, 49 bytes

(a,b)=>((c=Math.atan2)(...b)-c(...a))/Math.PI*180

Input is taken in form: [aY, aX], [bY, bX] (notice the reversed x/y)

Mwr247
la source
1

Simplex v.0.7, 13 bytes

I'm glad I added mathrelations :D Unfortunately, I cannot take pointwise input. So, I input each point as a separate number (Ax, Ay, Bx, By). (I used this as a resource.)

(iRi~^fR)2LSo
(       )2    ~~ repeat inner twice
 iRi          ~~ take two chars of input (x,y)
    ~         ~~ switch top 2 on stack
     ^f       ~~ apply atan2 on (y,x)
       R      ~~ go right
          L   ~~ go left
           S  ~~ subtract result
            o ~~ output as number

I can save a char if I can take input as (Ay, Ax, By, Bx):

(iRi^fR)2LSo
Conor O'Brien
la source
1

C, 88 bytes

#include<math.h>
typedef double d;d g(d x,d y,d a,d b){return atan2(b-y,a-x)*180/M_PI;}

Requires compiling with GCC to take advantage of M_PI being defined in math.h as a part of GCC's built-in math constants. Try it online - since ideone doesn't use GCC (apparently), an additional few bytes are needed for enough digits of π to be accurate.

Mego
la source
Or 45/atan(1) instead of 180/3.14159.... (in the online demo).
CompuChip
@CompuChip I wasn't trying to make the online demo maximally golfed
Mego
You can remove the brackets round atan2(b-y,a-x), although you then need a space after return so it only saves 1 byte. If you can use K&R style functions then double g(x,y,a,b)double x,y,a,b; also saves six bytes.
Alchymist