g | x | w | all
Bytes Lang Time Link
083C250613T112657ZToby Spe
011Stax180504T033453Zrecursiv
130C170416T193139ZAbel Tom
015APLDyalog Unicode250613T151136ZMat_rdv
117Tcl180503T234530Zsergiol
103C tcc240227T204532ZRosario
008Vyxal ḋ231223T204049Zemanresu
064APLNARS231223T081723ZRosario
056PowerShell Core210811T184745Zmazzy
070PowerShell Core210811T024036ZJulian
092Java170420T134634ZGerold B
6015MMIX210420T194952ZNoLonger
037Julia210420T231139ZMarcMush
020Husk210420T165914ZDominic
030Wolfram Language Mathematica210420T165631Zatt
036Desmos210420T163711ZEthan Ch
047R170417T192702ZGiuseppe
146F#180504T120859ZCiaran_M
035Pari/GP180104T085302Zalephalp
077Clean180104T032034ZΟurous
017J180104T023736Zcole
01105AB1E170416T195908ZEmigna
053Perl 6180103T190113ZSean
024J180103T062452ZBolce Bu
033Pyt171226T204848Zmudkip20
040TIBasic170417T033258Zpizzapan
157Operation Flashpoint scripting language170416T220212ZSteadybo
031Mathematica170416T183427ZGamrCorp
036Axiom170416T230646Zuser5898
076PHP170418T012842ZTitus
071C170417T202649ZHagen vo
061Haskell170417T001642ZJulian W
016Pyth170417T122258ZSteven H
046JavaScript ES6170416T205159ZNeil
096C170416T212813ZKhaled.K
011Jelly170417T040116ZJonathan
012Jelly170417T000826ZDennis
059JavaScript170416T194723Zfəˈnɛtɪk
071Haskell170416T230657ZEnderper
060JavaScript ES7170416T203215ZBál
022Jelly170416T220625Zfireflam
054Python170416T205615ZNeil
038oK170416T204828Zzgrep
057MATLAB with Symbolic Math Toolbox170416T190622ZLuis Men
014MATL170416T184601ZLuis Men

C, 84 83 bytes

float f(n,x)float x;{float c=1,t=1,i=2;for(;i<n*2;i+=2)c+=t*=x*x/(i-i*i);return c;}

How it works

float f(int n, float x)
{
    float sum = 1, term = 1;
    for (int i = 2;  i < n*2;  i += 2) {
        term *= -x*x / (i-1) / i;
        sum += term;
    }
    return sum;
}

Demo

#include <stdio.h>
int main(void)
{
    printf("| n | %9.6f | %9.6f | %9.6f |\n", 0.0, 0.5, 2.0);
    printf("|---|----------:|----------:|----------:|\n");
    for (int i = 1;  i <= 9;  ++i) {
        printf("| %d | %+09.6f | %+09.6f | %+09.6f |\n",
                  i,  f(i, 0), f(i, 0.5), f(i, 2.0));
    }
}
n 0.000000 0.500000 2.000000
1 +1.000000 +1.000000 +1.000000
2 +1.000000 +0.875000 -1.000000
3 +1.000000 +0.877604 -0.333333
4 +1.000000 +0.877582 -0.422222
5 +1.000000 +0.877583 -0.415873
6 +1.000000 +0.877583 -0.416155
7 +1.000000 +0.877583 -0.416147
8 +1.000000 +0.877583 -0.416147
9 +1.000000 +0.877583 -0.416147

Stax, 12 11 bytes

ä²>y9鲯d☼▒

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

            Input is `x n`
Z           Push a zero underneath the top.  The stack is now `x 0 n` 
D           Run the rest of the program n times.
  xJNi#     (-x*x)^i where i is the iteration index
  iH|F/     divide that by factorial(2i)
  +         add to the running total so far
            final result is implicitly printed

Run this one

C 144 130 bytes

F(m){int u=1;while(m)u*=m--;return u;}float f(float x,n){float s;for(int i=1;i<n;i++)s+=pow(-1,i)*pow(x,2*i)/(F(2*i));return 1+s;}

Ungolfed Version:

//Function to calculate factorial
int F(int m)
{
  int u=1;

  while(m>1)
   u*=m--; 
 
  return u;
}

//actual function called in main function   
float f(float x, int n)
{

  float s=0.0;

  for(int i=1;i<=n-1;i++)
     s+=pow(-1,i)*pow(x,2*i)/(F(2*i)); 
  
  return 1+s;
 }

Thanks Kevin for saving some bytes!

APL(Dyalog Unicode), 15 bytes SBCS

{-/(⍺∘*÷!)2×⍳⍵}

Try it on APLgolf!

Needs Index Origin 0 (⎕IO←0). x is a left argument and n is a right argument.

Explanation

             ⍵    the right argument (n)
            ⍳      Index Generator (numbers from 0 to n-1)
           ×       Multiply
          2    
   (     )         tacit function: (f g h) Y ←→ (f Y) g (h Y)
        !          Factorial
       ÷           Divide
      *            Power
     ∘             Bind
    ⍺              the left argument (x)
    ⍺∘*            power of x
  /                Reduce (from right to left)
 -                 
 -/                alternating series

Tcl, 117 bytes

proc c {x n k\ 0} {proc F n {expr $n?($n)*\[F $n-1]:1}
time {append r +-1**$k*$x**(2*$k)/[F 2*$k]
incr k} $n
expr $r}

Try it online!


# [Tcl], 126 bytes
proc c {x n k\ 0 r\ 0} {proc F n {expr $n?($n)*\[F $n-1]:1}
time {set r [expr $r+-1**$k*$x**(2*$k)/[F 2*$k]]
incr k} $n
set r}

Try it online!

C (tcc), 103 bytes

double r,d,m,co(int n,double w){int x=-1,y=0;for(r=d=1,m=-w*w;--n>0;x+=2,y+=2,r+=d*=m/(x*y));return r;}

Try it online!

Vyxal , 8 bytes

ʁd~e$¡/∑

Try it Online! The flag is to output as a decimal.

ʁ        # Range from 0 to n-1
 d       # doubled
  ~e     # x ** each of that
      /  # Divided by
    $¡   # Factorial of each of that
       ∑ # Sum

APL(NARS), 64 chars

r←p C w;d;v;m
r←d←1⋄m←w×wׯ1⋄v←¯1,0
→0×⍳0≥p-←1⋄r+←d×←m÷×/v+←2⋄→2

13+21+28+2=64

How to use and test:

  {⍵,⍵ C 0.5} ¨ 0..5
┌6─────────────────────────────────────────────────────────────────────────────┐
│┌2───┐ ┌2───┐ ┌2───────┐ ┌2──────────────┐ ┌2──────────────┐ ┌2──────────────┐│
││ 0 1│ │ 1 1│ │ 2 0.875│ │ 3 0.8776041667│ │ 4 0.8775824653│ │ 5 0.8775825622││
│└~───┘ └~───┘ └~───────┘ └~──────────────┘ └~──────────────┘ └~──────────────┘2
└∊─────────────────────────────────────────────────────────────────────────────┘

OT these below should be the answers 100% precise but not in decimal

  {⍵,⍵ C 1r2} ¨ 0..5
┌6─────────────────────────────────────────────────────────────────────────┐
│┌2───┐ ┌2───┐ ┌2─────┐ ┌2─────────┐ ┌2─────────────┐ ┌2──────────────────┐│
││ 0 1│ │ 1 1│ │ 2 7r8│ │ 3 337r384│ │ 4 40439r46080│ │ 5 9058337r10321920││
│└~───┘ └~───┘ └~─────┘ └~─────────┘ └~─────────────┘ └~──────────────────┘2
└∊─────────────────────────────────────────────────────────────────────────┘

7r8 means 7/8 .

PowerShell Core, 59 56 bytes

-3 bytes thanks to Julian

param($x,$n)$v=1
1..$n|%{$s+=$v;$v*=-$x*$x/++$k/++$k}
$s

Try it online!

PowerShell Core, 89 70 bytes

param($x,$n)0..--$n|%{$s+="-$x*$x*"*$_+(1..(2*$_)-ne0-join'/')|iex}
$s

Try it online!

Explanation

Generates a string containing each of the member of the sum like

-0.5*0.5*-0.5*0.5*0.5*-0.5*0.5*-0.5*1/2/3/4/5/6/7/8

Then pass it through iex and sums the different iterations.

-6 bytes thanks to mazzy!

Java, 92 bytes

double c(double x,double c,long d,int i){return i>0?r+=c(x,-c/x/x,d/(4*i*i-2*i),--i)+c/d:r;}

Try it online!

With comments and whitespaces:

C.java

    /*
     * Class 'C' (for 'Cosine').
     * Copyright (C) 2017 Gerold 'Geri' Broser (geribro@users.sourceforge.net)
     * 
     * This program is free software: you can redistribute it and/or modify
     * it under the terms of the GNU General Public License as published by
     * the Free Software Foundation, either version 3 of the License, or
     * (at your option) any later version.
     * 
     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
     * GNU General Public License for more details.
     * 
     * You should have received a copy of the GNU General Public License
     * along with this program. If not, see <http://www.gnu.org/licenses/>.
     */
    //package p;
    
    /** Class 'C' (for Cosine).
     *  
     * @author Gerold 'Geri' Broser
     * @version 17.04.21
     * @see https://codegolf.stackexchange.com/questions/116705/the-pedants-cosine
     */
    class C {
    
        /** The added up results of the polynomial's terms.
         */
        double r;

        /** This one-liner method 'c' (for calculate) returns the part (i=n-1) of a 
         *  cosine of a given angle 'x' that's calculated from the second term of a
         *  Taylor series of n polynomial terms onwards (or backwards until the 
         *  second term [i=1], to be precise, see below).
         *  
         *  It achieves this by doing the following:
         * 
         * ● It doesn't calculate the first term since it is always 1 anyway.
         * 
         * ● It uses recursion for calculating the terms of the polynomial.
         * 
         * ● It calculates from the rightmost term back to the leftmost. Such avoiding
         *   to keep the upper boundary stored till the end for the recursion's stop 
         *   condition.
         * 
         * ● It is supplied with values for the counter and denominator of the 
         *   rightmost term at invocation. Such also the user can decide which
         *   library to take for power and factorial. 
         * 
         * ● It calculates the counters and denominators for each term from scratch 
         *   at each recursion but uses the values calculated at the previous 
         *   recursion. Such the new values can be calculated by using trivial 
         *   parenthesis, division, multiplication, decrement and negation only.
         *   This doesn't only save characters but probably is also faster than 
         *   power and factorial.
         *   [It could be made be even faster for x=2^n, n ∈ N, because we can 
         *   use the unsigned right shift operator '>>>' instead of divisions then
         *   (see method 'calculateForXisPowerOfTwo()' of class 'Cosine').]
         * 
         * @param x angle (independent variable) in radians
         * @param c counter of last term specified by index 'i' including proper sign
         *          (see class 'CTest')
         * @param d denominator of last term specified by index 'i' (see class 'CTest')
         * @param i index of last term used in the calculation (=number of terms 'n'
         *          minus 1; Σ's upper boundary)
         * 
         * @see https://en.wikipedia.org/wiki/Taylor_series#Trigonometric_functions
         */
    
        // Copy the following three lines to immediately after the function header for testing: 
        //  System.out.printf(
        //          "c(): x:%4.1f  c:%24.17f  d:%,19d  i:%2d  t:%40.35f%n",
        //          x, c, d, i, c / d);
    
        // Position of 'i' is relevant here, since it is prefix-decremented inline!
        double c( double x, double c, long d, int i ) {
            return i > 0
                    ? r += c(
                        x,
                        -c / x / x,
                        d / (4 * i * i - 2 * i),
                        --i )
                        + c / d
                    : r;
        } // c()
    } // C

CTest.java

    /*
     * Class 'CTest' (for 'Cosine Test').
     * Copyright (C) 2017 Gerold 'Geri' Broser (geribro@users.sourceforge.net)
     * 
     * This program is free software: you can redistribute it and/or modify
     * it under the terms of the GNU General Public License as published by
     * the Free Software Foundation, either version 3 of the License, or
     * (at your option) any later version.
     * 
     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
     * GNU General Public License for more details.
     * 
     * You should have received a copy of the GNU General Public License
     * along with this program. If not, see <http://www.gnu.org/licenses/>.
     */
    package p;
    
    import org.apache.commons.math3.util.CombinatoricsUtils;
    
    /** Test class for methods 'c' (for calculate) of class 'C' (for Cosine).
     * 
     * @author Gerold 'Geri' Broser
     * @version 17.04.21
     * @see https://codegolf.stackexchange.com/questions/116705/the-pedants-cosine
     */
    public class CTest {
    
        /** The Unicode character 'ₛ' is the subscript character for 's'. It stands for the plural 's' 
         *  in the array's names. ('xs' wasn't matching my BMI. 'ns' looked like a system that we have
         *  overcome since decades and like the German abbreviation for...I'm leaving that one out now.)
         * 
         * @param args command line arguments
         */
        public static void main( String[] args ) {
    
            double[] xₛ = { .0, .5, .5, .5, .5, 2., 2. };
            int[] nₛ = { 1, 1, 2, 4, 9, 2, 5 };
    
            System.out.println(
                    "┌────┬─────┬───┬───────────────────────┐\n" +
                    "│ No │  x  │ n │        cos(x)         │\n" +
                    "├────┤─────┼───┼───────────────────────┤" );
            for ( int i = 0; i < xₛ.length; i++ ) {
    
                System.out.printf( "│ %d. │ %2.1f │ %d │ %,21.18f │%n",
                        i + 1,
                        xₛ[i], // x (angle)
                        nₛ[i]--, // n (number of terms of the polynomial, decreased for further processing as index)
                        1.0 + new C().c(
                                xₛ[i], // x (angle in radians)
                                Math.pow( -1, nₛ[i] ) // negate alternating starting with minus for the second term 
                                        * Math.pow( xₛ[i], 2 * nₛ[i] ), // counter for the rightmost term (c)
                                CombinatoricsUtils.factorial( 2 * nₛ[i] ), // denominator for the rightmost term (d)
                                nₛ[i] // index of last term of the polynomial 
                        ) );
    
            } // for ( C test case )
            System.out.println( "└────┴─────┴───┴───────────────────────┘" );
        } // main()
    } // CTest

Output

┌────┬─────┬───┬───────────────────────┐
│ No │  x  │ n │        cos(x)         │
├────┤─────┼───┼───────────────────────┤
│ 1. │ 0,0 │ 1 │  1,000000000000000000 │
│ 2. │ 0,5 │ 1 │  1,000000000000000000 │
│ 3. │ 0,5 │ 2 │  0,875000000000000000 │
│ 4. │ 0,5 │ 4 │  0,877582465277777700 │
│ 5. │ 0,5 │ 9 │  0,877582561890372800 │
│ 6. │ 2,0 │ 2 │ -1,000000000000000000 │
│ 7. │ 2,0 │ 5 │ -0,415873015873015950 │
└────┴─────┴───┴───────────────────────┘

MMIX, 60 bytes (15 instrs)

cos SETH $5,#3FF0       // E0053FF0: one = 1.0
    SETL $2,0           // E3020000: twon = 0
    SET  $3,$5          // C1030500: term = one
    FMUL $4,$0,$0       // 10040000: numer = x *. x
    SETL $0,0           // E3000000: accum = 0
    INCH $4,#8000       // E4048000: numer = -.numer
0H  FADD $0,$0,$3       // 04000003: loop: accum +.= term
    FADD $255,$2,$5     // 04FF0205: temp = twon +. 1
    FADD $2,$255,$5     // 0402FF05: twon = temp +. 1
    FMUL $255,$255,$2   // 10FFFF02: temp *.= twon
    FDIV $255,$4,$255   // 14FF04FF: temp = numer /. temp
    FMUL $3,$3,$255     // 100303FF: term *.= temp
    SUBU $1,$1,1        // 27010101: count--
    PBZ  $1,0B          // 5301FFF9: likelyif(!count) goto loop
    POP  1,0            // F8010000: return(accum)

This is a really simpleminded algorithm. I managed to avoid using more than three stack temporaries ($255 is global and free for temporary use, any register numbered less than 32 is guaranteed on-stack).

A few clever tricks and misc notes:
SET $X,$Y is a short version of OR $X,$Y,0;
it's nice that 1.0 fits entirely in the top quarter of a float, otherwise we would have had to use another instruction to set it;
PBZ is a predicted branch (faster if taken) if the register operand is 0;
the 0H is a local label that the 0B refers back to; and POP a,b means return a local variables and skip b instructions after the function call.

Julia, 37 bytes

x$n=1>(n-=1)||x$n+(-x^2)^n/prod(1:2n)

Try it online!

Husk, 20 bytes

⌊*!9İ⁰ṁ§/ȯΠḣD`^o_□⁰ŀ

Try it online!

Outputs sign + 9 decimal places; the initial decimal point is implicit.

14 bytes (ṁ§/ȯΠḣD`^o_□⁰ŀ) to calculate the cosine, plus 6 bytes (⌊*!9İ⁰) to extract the decimal representation from the a rational number...

Wolfram Language (Mathematica), 30 bytes

Normal[Cos@x+O@x^(2#2)]/.x->#&

Try it online!

Mathematica has a more (byte-)efficient way to generate SeriesData objects than Series. O[x]^p truncates the power series of the function at the pth power.

Desmos, 36 bytes

\sum_{k=0}^{n-1}{(-1)^kv^{2k}/(2k)!}

View it on Desmos

Unfortunately, not a ton to golf here.

R, 70 64 47 bytes

function(x,n,m=1:n-1)sum((-x^2)^m/gamma(2*m+1))

Try it online!

Thanks to Dominic van Essen for golfing 17 bytes off by using a basic R feature: vectorization!

F#, 177 146 bytes

let rec f x=if x<2 then 1 else f(x-1)*x
let i n x=(pown -1.0 n)*(pown x (2*n))/float(f(2*n))
let t x k=seq{for j=0 to(k-1)do yield i j x}|>Seq.sum

Try it online!

Shaved off 31 bytes thanks to Emmanuel showing me operators in F# that I wasn't aware of. I had a look at Microsoft.FSharp.Core.Operators and found some useful stuff there. Thanks a million!

f is a recursive factorial function. i is one item in the series, and t is the actual Taylor Series itself - iterate through from 0 to k-1, evaluating i at each stage, and sum the results.

Pari/GP, 35 bytes

f(x,n)=sum(i=0,n-1,(-x^2)^i/(2*i)!)

Try it online!

Clean, 77 bytes

import StdEnv
?x n=sum[(-1.0)^(p/2.0)*x^p/prod[1.0..p]\\p<-take n[0.0,2.0..]]

Try it online!

J, 17 bytes

4 :'2&o.T.(+:y)x'

Try it online!

Uses a built-in, which I assume is OK.

Unfortunately, I don't really know how to work well with functions that take arguments via currying like this, so I had to do this explicitly. I'm sure that there is a way to do it tacitly or shorter.

05AB1E, 14 11 bytes

FIn(NmN·!/O

Try it online!

Explanation

F                # for N in [0 ... n] do
 In              # push (x^2)
   (             # negate
    Nm           # raise to the Nth power
      N·!        # push (2*N)!
         /       # divide
          O      # sum

Perl 6, 53 bytes

{(sum (1,*i*$^x...*)[^2*$^n] »/»(1,|[\*] 1..*)).re}

Try it online!

This actually computes the complex exponential e for twice the number of requested terms and then takes the real part.

J, 26 24 Bytes

+/@:(!@]%~^*_1^2%~])2*i.

-2 bytes thanks to @cole

I originally planned to use a cyclic gerund to alternate between adding and subtracting, but couldn't get it to work.

Explanation:

                    2*i.     | Integers from 0 to 2(n-1)
    (              )         | Dyadic train:
            _1^-:@]          | -1 to the power of the left argument
          ^*                 | Times left arg to the power of right arg
     !@]%~                   | Divided by the factorial of the right arg
+/@:                         | Sum

Pyt, 37 34 33 bytes

←←ĐĐ↔3Ș1~⇹ř⁻^04Ș⇹ř⁻^²*0↔ř⁻2*!+/+Ʃ

TI-Basic, 41 40 bytes

Prompt X,N
sum(seq((-(X+1E-49)2)^Q/((2Q)!),Q,0,N-1
1E-49 is added to the angle because TI-Basic throws an error for 0^0, it's just large enough to not cause the error, and it is not large enough to change the answer.

Operation Flashpoint scripting language, 165 157 bytes

F={x=_this select 0;n=_this select 1;i=0;r=0;while{i<n*2}do{r=r+x^i/(i call{c=_this;j=c-1;while{j>0}do{c=c*j;j=j-1};if(c<1)then{c=1};c})*(-1)^(i/2);i=i+2};r}

Call with:

hint format["%1\n%2\n%3\n%4\n%5\n%6\n%7",
    [0.0, 1] call f,
    [0.5, 1] call f,
    [0.5, 2] call f,
    [0.5, 4] call f,
    [0.5, 9] call f,
    [2.0, 2] call f,
    [2.0, 5] call f]

Output:

enter image description here

Input and output should be floating-point values, at least as accurate as calculating the formula using single-precision IEEE floating point numbers with some standard rounding rule.

I'm fairly sure that the numbers are single-precision IEEE floating point numbers, even though in the printed output the longer decimals are not that precise. It is the printing that rounds the numbers like that, actually the numbers are more precise.

For instance, a=1.00001;b=1.000011;hint format["%1\n%2\n%3", a, b, a==b] will output this:

1.00001
1.00001
false

So clearly the actual precision of the numbers is greater than the printed precision.

Mathematica, 49 41 39 31 bytes

Sum[(-#^2)^k/(2k)!,{k,0,#2-1}]&

Old, more "fun" version: (39 bytes)

Normal@Series[Cos@k,{k,0,2#2-2}]/.k->#&

Saved 10 bytes thanks to @Pavel and 8 thanks to @Greg Martin!

Axiom, 36 bytes

g(a,n)==eval(taylor(cos(x)),a).(2*n)

Build the infinite (in the meaning finite but one can ask to build the list of 2*n elements if PC has enough memory) list of partial sums for the Taylor series for cos(x) calculate in 'a', in "eval(taylor(cos(x)),a)"; gets the 2*n element of that list in ".(2*n)". Test cases:

(47) -> g(0,1)
   (47)  1
                                                 Type: Expression Integer
(48) -> g(0.5,1)
   (48)  1.0
                                                   Type: Expression Float
(49) -> g(0.5,2)
   (49)  0.875
                                                   Type: Expression Float
(50) -> g(0.5,4)
   (50)  0.8775824652 7777777778
                                                   Type: Expression Float
(51) -> g(0.5,9)
   (51)  0.8775825618 9037271611
                                                   Type: Expression Float
(52) -> g(2.0,5)
   (52)  - 0.4158730158 7301587302
                                                   Type: Expression Float
(53) -> g(2.0,800)
   (53)  - 0.4161468365 471423870

PHP, 76 bytes

for($f=1;$i<$argv[2]*2;$f*=++$i)$i&1?:$s+=(-1)**$k++*$argv[1]**$i/$f;echo$s;

takes X and N from command line arguments; run with -r.

loop $i from 0 to N*2-1, hold fac($i) in $f; if $i is even, add term to sum$s. print sum.


I wish I had complex numbers (with M_I as imaginary unit);
I would simply multiply $f with M_I*++$i and save 7 bytes.

Maybe Mathematica can do that. But Mathematica doesn´t have to.

I could save two bytes with cos(M_PI*$i/2) instead of $i&1?: and (-1)**$k++;
but it would feel a bit odd to use a cosine builtin to build a cosine function.

C, 71 bytes

using Horner scheme

float f(n,x)float x;{float y;for(n+=n;n;)y=1-(y*x*x/n--)/n--;return y;}

Ungolfed version:

float f(n,x) float x;
{
  float y = 0.0;
  for(n = 2*n; n>0; n -= 2)
  {
    y = 1-y*x*x/n/(n-1);
  }
  return y;
}

Haskell, 61 bytes

x#n=sum[(-1*x^2)^i/fromIntegral(product[1..2*i])|i<-[0..n-1]]

This seemed different enough from the other Haskell solution to warrant a separate answer. Implementation should be pretty self-explanatory—call with x#n where x is the number the cosine of which is to be computed and n is the order of the partial sum to be taken.

Pyth, 16 bytes

sm_Fc^vzyd.!yddU

Accepts n first, then x. Example run.

JavaScript (ES6), 46 bytes

f=
x=>g=(n,t=1,p=0)=>n&&t+g(--n,-t*x*x/++p/++p,p)
<div oninput=o.textContent=f(x.value)(n.value)><input id=x><input type=number min=1 value=1 id=n><pre id=o>1

Takes curried inputs (x)(n).

C, 96 bytes

Recursive Live

f(n){return n?n*f(n-1):1;}float c(n,x)float x;{return n?c(n-1,x)+pow(-1,n)*pow(x,2*n)/f(2*n):1;}

Detailed

f(n) // factorial(n)
{
    return n ?   // n != 0 ?
        n*f(n-1) // n! = n * (n-1)!
    : 1;         // 0! = 1
}

float c(n,x)float x; // cos(x) with n+1 terms
{
    return n ?        // n != 0 ?
        c(n-1, x)     // cos(x) (n-1)th term
        + pow(-1, n)  // + (-1)^n
        * pow(x, 2*n) // * x^(2n)
        / f(2 * n)    // / (2n)!
    : 1;              // cos(x) at n=0
}

Progressive Recursive, 133 bytes Live

#define F float
#define c(x,n) 1+g(1,n,x,1,1,1)
F g(F i,F n,F x,F s,F p,F f){s=-s;p*=x*x;f*=i;return i<n?g(i+1,n,x,s,p,f)+s/2*p/f:0;}

Detailed

#define F float // shorthand float

#define c(x,n) 1+g(1,n,x,1,1,1) // macro function

F g(F i,F n,F x,F s,F p,F f)
{
    s = -s;   // (-1)^n = (-1) * (-1)^(n-1)
    p *= x*x; // x^(2n) =  x^2 * x^(2(n-1))
    f *= i;   //    2n! =    2 * (1*2*..*n)

    return i < n ?       // i = 0 .. n-1
        g(i+1,n,x,s,p,f) // next term
        + s / 2 * p / f  // s*p/2f = s/2*p/f
        : 0;             // don't compute nth term
}

Jelly, 12 11 bytes

ḶḤµ⁹*÷!_2/S

Try it online!

How?

ḶḤµ⁹*÷!_2/S - Main link: n, x           e.g. 5, 2.0
Ḷ           - lowered range(n)              [0,1,2,3,4]
 Ḥ          - double (vectorises)           [0,2,4,6,8]
  µ         - monadic chain separation (call that i)
   ⁹        - link's right argument         2.0
    *       - exponentiate(i) (vectorises)  [1.0,4.0,16.0,64.0,256.0]
      !     - factorial(i) (vectorises)     [1,  2,  24,  720, 40320]
     ÷      - divide (vectorises)           [1.0,2.0,0.6666666666666666,0.08888888888888889,0.006349206349206349]
        2/  - pairwise reduce by:
       _    -     subtraction               [-1.0,0.5777777777777777,0.006349206349206349]
         S  - sum                           -0.41587301587301617

Jelly, 12 bytes

²N*Ḷ}©÷®Ḥ!¤S

Try it online!

How it works

²N*Ḷ}©÷®Ḥ!¤S  Main link. Left argument: x. Right argument: n

²             Square; yield x².
 N            Negate; yield -x².
     ©         Call the link to the left and copy the result to the register.
   Ḷ}          Call unlength on the right argument, yielding [0, 1, ..., n-1].
  *           Yield [1, -x², ..., (-x²)**(n-1)].
          ¤   Combine the three links to the left into a niladic chain.
       ®        Yield the value in the register, [0, 1, ..., n-1].
        Ḥ       Unhalve; yield [0, 2, ..., 2n-2].
         !      Factorial; yield [0!, 2!, ..., (2n-2)!].
      ÷         Division; yield [1/0!, -x²/2!, ..., (-x²)**(n-1)/(2n-2)!].
           S  Take the sum.

JavaScript, 59 bytes

x=>k=n=>--n?k(n)+(-1)**n*x**(n*=2)/f(n):1
f=p=>p?p*f(p-1):1

Try it online!

Haskell, 71 Bytes

f x n=sum$map(\i->(-1)^i*x^(2*i)/fromIntegral(product[1..2*i]))[0..n-1]

This is a pretty boring answer that's not too hard to decipher. The fromIntegral really bites, though. (The / operator requires operands of the same numeric type in Haskell, and coercing between numeric types is not allowed without a wordy function.)

JavaScript ES7 60 bytes

x=>a=n=>--n?(-1)**n*x**(2*n)/(f=m=>m?m*f(m-1):1)(2*n)+a(n):1


x=>a=n=>                                                         // Curry-d function, it basically returns another function
        --n?                                              :1  // subtract one from n. If n - 1 is 0, return 1
            (-1)**n*                                             // This generates the sign of the number
                    x**(2*n)/                                    // This creates the part before the division, basicaly x^2n
                             (f=m=>m?m*f(m-1):1)(2*n)            // This creates a recursive factorial function and calls it with 2n
                                                     +a(n)    // Recursively call the function. This adds the elements of the taylor series together

To use it:

Press F12, type in the function and then do

c(x)(n)

Jelly, 22 bytes

-*ð×ø⁹*⁸²ð÷ø⁸Ḥ!
⁸R’Ç€S

This is a full program which takes n as the first argument and x as the second.

Explanation:

              Creates a function to compute each term in the series. 
Its argument we will call k, eg k=3 computes 3rd term. Take x=2 for example.
-*           Computes (-1)^k. Eg -1
ð×ø        Multiplies by the quantity of
⁹             x.  
*             to the power of
⁸             k
²             ...squared. Eg -1 × (2³)² 
ð÷ø        divides by the quantity of
⁸              k
Ḥ             doubled
!               ...factorial. Eg -1 × (2³)²/(6!).


                Main link, first argument n and second argument n. Eg n=4, x=2.
⁸R            Creates range(n). Eg [1,2,3,4]
’                Decrements each element. Eg [0,1,2,3]
Ç€            Maps the above function over each element. Eg [1,-2,0.666,-0.0889]
S               Sum all all of the elements.  Eg -0.422.

Python, 54 bytes

f=lambda x,n,t=1,p=1:n and t+f(x,n-1,-t*x*x/p/-~p,p+2)

If using Python 2, be sure to pass x as a float, not an integer, but I my understanding is that it doesn't matter if you're using Python 3.

oK, 38 bytes

This also works in k, but takes 39 bytes because one ' has to be written as /: instead (at least, in kmac 2016.06.28 it does).

{+/(y#1 -1)*{(*/y#x)%*/1+!y}.'x,'2*!y}

Explanation:

Let's start with the middle bit. (*/y#x) is exponentiation, it is equivalent to x^y. */1+!y would be y!, or y factorial. % is division. Therefore the function in the middle is middle(x,y) = (x^y)/(y!).

Now the bit on the right, to which the function above gets applied. 2*!y is {0, 2, 4, ..., 2*(y-1)}. x,' prepends x to every item in that list, turning it into {(x, 0), (x, 2), (x, 4), ..., (x, 2*(y-1))}. The .' then applies middle to every pair of numbers (map, essentially).

Finally, (y#1 -1)* multiplies the result by 1 or -1 (alternating), and +/ takes the sum.

MATLAB with Symbolic Math Toolbox, 57 bytes

@(x,n)eval(subs(taylor(sym('cos(x)'),'Order',2*n),'x',x))

This defines an anonymous function with that takes double inputs x,n and outputs the result as a double.

Example (tested on R2015b):

>> @(x,n)eval(subs(taylor(sym('cos(x)'),'Order',2*n),'x',x))
ans = 
    @(x,n)eval(subs(taylor(sym('cos(x)'),'Order',2*n),'x',x))
>> f = ans; format long; f(0,1), f(0.5,1), f(0.5,2), f(0.5,4), f(0.5,9), f(2,2), f(2,5)
ans =
     1
ans =
     1
ans =
   0.875000000000000
ans =
   0.877582465277778
ans =
   0.877582561890373
ans =
    -1
ans =
  -0.415873015873016

MATL, 14 bytes

U_iqE:2ep/YpsQ

Try it online! Or verify all test cases.

Explanation with example

All numbers have double precision (this is the default).

Consider inputs x = 2.0, n = 5.

U_     % Implicitly input x. Square and negate
       % STACK: -4
iqE    % Input n. Subtract 1, multiply by 2
       % STACK: -4, 8
:      % Range
       % STACK: -4, [1 2 3 4 5 6 7 8]
2e     % Reshape into a 2-row matrix
       % STACK: -4, [1 3 5 7;
       %             2 4 6 8]
p      % Product of each column
       % STACK: -4, [2 12 30 56]
/      % Divide, element-wise
       % STACK: [-2 -0.333333333333333 -0.133333333333333 -0.0714285714285714]
Yp     % Cumulative product of array
       % STACK: [-2 0.666666666666667 -0.0888888888888889 0.00634920634920635]
s      % Sum of array
       % STACK: -1.41587301587302
Q      % Add 1. Implicitly display
       % STACK: -0.41587301587302