Las matrices comienzan en


10

Su tarea es tomar una matriz de números y un número real y devolver el valor en ese punto de la matriz. Las matrices comienzan en y se cuentan en intervalos . La cuestión es que en realidad vamos a interpolar entre elementos dados el "índice". Como ejemplo:ππ

Index:    1π   2π   3π   4π   5π   6π
Array: [ 1.1, 1.3, 6.9, 4.2, 1.3, 3.7 ]

Debido a que es π , tenemos que hacer la trigonometría obligatoria, por lo que utilizaremos la interpolación de coseno utilizando la siguiente fórmula:

cos⁡(imodπ)+12∗(α−β)+β

dónde:

  • i es el "índice" de entrada
  • α es el valor del elemento inmediatamente anterior al "índice"
  • β es el valor del elemento inmediatamente después del "índice"
  • cos toma su ángulo en radianes

Ejemplo

Dado [1.3, 3.7, 6.9], 5.3:

El índice 5.3 está entre y , por lo que 1.3 se usará para y 3.7 se usará para . Poniéndolo en la fórmula, obtenemos:1π2πbeforeafter

cos⁡(5.3modπ)+12∗(1.3−3.7)+3.7

Que sale a 3.165

Notas

  • La entrada y salida pueden estar en cualquier formato conveniente
  • Puede suponer que el número de entrada es mayor que y menor que *πarray lengthπ
  • Puede suponer que la matriz de entrada tendrá al menos 2 elementos de longitud.
  • Su resultado debe tener al menos dos puntos decimales de precisión, ser exacto dentro de 0.05 y admitir números hasta 100 para esta precisión / exactitud. (los flotadores de precisión simple son más que suficientes para cumplir con este requisito)

¡Feliz golf!


8
FYI golfistas, podría ser más corto escribir reescribir como cos ( x / 2 ) 2 usando la fórmula de medio ángulo para cos . (cos⁡(X)+1)/ /2cos⁡(X/ /2)2cos
— xnor

¿Puedo tomar un diccionario con dobles como claves? Los dobles serán números enteros, por supuesto.
— Encarnación de la ignorancia

@EmbodimentofIgnorance, claro. Dudo que eso te ayude, pero es una representación perfectamente razonable de las matrices, ya que así es como lo hace Lua.
— Beefster

@KevinCruijssen No veo por qué eso importaría. 3.7 está entre pi y 2pi.
— Beefster

Respuestas:


5

R , 59 53 bytes

function(x,i)x[0:1+i%/%pi]%*%c(a<-cos(i%%pi/2)^2,1-a)

Pruébalo en línea!

Aquí no hay nada demasiado inteligente: solo una versión R de la fórmula en la pregunta. Gracias a @MickyT por guardar un byte, y a @Giueseppe e indirectamente a @xnor por otros dos, y a @RobinRyder por guardar otros 3.


Creo que se puede soltar un byte con...*(cos(i%%pi)+1)/2
— MickyT

@MickyT gracias, originalmente había puesto el +1 entre paréntesis, pero había agregado un par de paréntesis redundantes para terminar con 60 bytes
— Nick Kennedy

56 bytes siguiendo el comentario de xnor sobre la fórmula de medio ángulo.
— Giuseppe


4

Python 3.8 (prelanzamiento) , 85 74 bytes

-8 bytes gracias a @xnor
-2 bytes gracias a @Quintec

Esto aprovecha el nuevo :=operador de asignación de la versión preliminar de Python 3.8 . Aparte de eso, esta es realmente la ecuación escrita en Python.

import math
lambda l,i:cos(i%math.pi/2)**2*(l[(j:=int(i/pi))-1]-l[j])+l[j]

Uso:

>>> p=lambda l,i:cos(i%math.pi/2)**2*(l[(j:=int(i/pi))-1]-l[j])+l[j]
>>> print(p([1.3, 3.7, 6.9],5.3))
3.165249203414993

Pruébalo en línea!


1
Simplemente puede asignar jel primer lugar que se menciona : parte del poder de las expresiones de asignación es que evalúan el valor y lo asignan.
— xnor

1
Guardar otro byte: Use trig identidades para convertir (cos(i%pi)+1)/2 acos(i%pi/2)**2
— XNOR

@xnor Buen punto. Sabía que estaba usando eso mal
— senox13

1
Puede descartarlo p=ya que las funciones anónimas están bien
— Quintec

1
Olvidé actualizar bytecount :)
— Quintec

3

Jalea , 17 bytes

d©ØPṪÆẠ‘H×I_@Ḋ}®ị

Un programa completo que acepta yo la matriz que imprime el valor interpolado.

Pruébalo en línea!

¿Cómo?

Interpola entre todos los vecinos usando cos⁡(yomodificaciónπ)+12 luego selecciona el valor relevante.

d©ØPṪÆẠ‘H×I_@Ḋ}®ị - Link: number, i; list of numbers, A
  ØP              - pi (ish) = 3.141592653589793
d                 - divmod = [i//pi, i%pi]
 ©                - (copy to register for later)
    Ṫ             - tail (gets i%pi leaving register copy as [i//pi])  
     ÆẠ           - cosine = cos(i%pi)
       ‘          - increment
        H         - halve
         ×        - multiply by A (vectorises)
          I       - increments -- i.e. (cos(i%pi)+1)(r-l)/2 for neighbours [l,r]
             Ḋ}   - dequeue A
           _@     - swapped arg subtract (vectorises) -- i.e. r-(cos(i%pi)+1)(r-l)/2
                  -                                         = r+(cos(i%pi)+1)(l-r)/2
               ®  - recall value from the register
                ị - index into (vectorises) -- i.e. [β+(cos(i%pi)+1)(α-β)/2]
                  - implicit print of Jelly representation (only 1 entry so [] wont appear)



1

Stax , 17 bytes

≈ëBü☺ÆssÅ¢â)KjjïΔ

Ejecutar y depurarlo

Desempaquetado, sin golf, y comentó que se ve así.

VP|%    divmod with pi;  push div and mod results separately
|7^h    do (cos(modpart) + 1) / 2
sX      swap the original div result to top of stack, store it in the x register
v       decrement
;:-     pairwise differences of array
@       get element at index
N*      negate and multiply
;x@     get element from the original array at the x index, where x is the register
+       add

Ejecute este



1

APL + WIN, 39 37 bytes

2 bytes guardados gracias a Adám

2⊃m+(-/m←⎕[0 1+⌊n÷○1])÷2÷1+2○(○1)|n←⎕

¡Pruébalo en línea! Dyalog Classic

Explicación:

n←⎕ prompt for input of integer

2÷1+2○(○1)|n evaluate first term of formula

[0 1+⌊n÷○1] identify indices of alpha and beta

m←⎕[...] prompt for input of vector and select alpha and beta

-/m alpha-beta

2⊃m+ take result of adding beta to complete the equation 


1

Haskell , 65 bytes

v!i|(c,r)<-properFraction$i/pi=cos(r*pi/2)^2*(v!!(c-1)-v!!c)+v!!c

Pruébalo en línea!

Nota: la matriz se representa como una lista.

Gracias a @xnor por la punta de medio ángulo.


0

Jalea , 23 20 18 bytes

³%ØPÆẠ×_++H
÷ØPịÇ/

Pruébalo en línea!

÷ØPịṁؽµ³%ØPÆẠ×I_@SH    Dyadic link, arguments x (index) and Z (array):
֯P                     x/pi
   ị                    Index (into Z).
                        When x/pi is an integer, returns that elt of Z.
                        Otherwise returns 2 elements at floor and ceiling.
     ؽ                   [1,2] (generic 2 element array)
    ṁؽ                 Mold; shape like [1,2] to ensure we have 2 elements.
       µ                Start a new, monadic chain with the result [a,b]
        ³%ØPÆẠ×I_@SH    Monadic chain
        ³               x
         %ØP            x mod pi
            ÆẠ          Unarccosine; cos(x mod pi).
               I          Increment; b-a.
              ×I        (b-a) cos(x mod pi)
                  S       a+b
                _@S     a + b - (b-a) cos(x mod pi)
                   H    Halve; this is equivalent to our desired result.

0

Adjunto , 54 bytes

${Cos[y%PI/2]^2*&`-@(j:=x[1'-1*Floor[y'-y/PI]-1])+j@1}

Pruébalo en línea!

Explicación

${Cos[y%PI/2]^2*&`-@(j:=x[1'-1*Floor[y'-y/PI]-1])+j@1}
${                                                   }  parameters: x, y
  Cos[y%PI/2]^2                                         the scaling function factor
               *                                        times
                     j:=                                set j to
                        x[                     ]        the element in x at
                          1'-1*Floor[y'-y/PI]-1         the closest indices scaled by PI
                &`-@(                           )       spread subtraction over bounds
                                                 +j@1   add the upper bound

0

C (GCC) 99 79 bytes

-Cat de techo de 20 bytes

float P=3.141593;b;
#define f(i,a)(cos(fmod(i,P))+1)/2*(a[b=i/P-1]-a[++b])+a[b]

Pruébalo en línea!

Código de llamada

int main() {
  float a[3] = {1.3,3.7,6.9};
  printf("%f\n", f(5.3,a));
}

tenga en cuenta que necesitaba el indicador del compilador -lmpara vincularse con las bibliotecas matemáticas, por lo que +3 bytes si cuenta eso.


0

05AB1E , 22 21 20 19 bytes

žq‰`ž>;UÝèÐÁ-θX*-θ

Pruébelo en línea o verifique algunos casos de prueba más .

Explicación:

žq‰        # Take the divmod PI of the (implicit) input-decimal
           # (part = input integer-divided by PI, remainder = input modulo-PI)
           #  i.e. 5.3 → [1, 2.158...]
   `       # Push both values separately to the stack
    ž     # Take the cosine of the remainder
           #  i.e. 2.158... → -0.554...
      >    # Increase it by 1
           #  i.e. -0.554... → 0.554...
       ;   # Halve it
           #  i.e. 0.554... → 0.222...
        U  # Pop and store it in variable `X`
    Ý      # Pop the part, and push a list in the range [0, part]
           #  i.e. 1 → [0, 1]
     è     # (0-based) index all of them into the (implicit) input-list
           #   i.e. [1.3, 3.7, 6.9] and [0, 1] → [1.3, 3.7]
Ð          # Triplicate this list
 Á         # Rotate the last copy once towards the right
           #  i.e. [1.3, 3.7] → [3.7, 1.3]
  -        # Subtract the values in the top two lists from one another
           #  i.e. [1.3, 3.7] and [3.7, 1.3] → [-2.4, 2.4]
   θ       # Pop and only leave the last value of this list
           #  i.e. [-2.4, 2.4] → 2.4
    X*     # Multiply it by `X`
           #  i.e. 2.4 * `X`=0.222... → 0.534...
     -     # Subtract it from each of the values in the list we triplicated
           #  i.e. [1.3, 3.7] - 0.534... → [0.765..., 3.165...]
      θ    # And only leave the last value of this list
           #  i.e. [0.765..., 3.165...] → 3.165...
           # (which is output implicitly as result)

Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.