Task: Create a list in the range from -n to n according to the following pattern: -n, n-1, - (n-2), n-3 ... Find the arithmetic mean of the list elements.

F # code:

open System let n = 20 let array = [| for i in 0 .. n -> if i%2=0 then ((ni)* -1) else ni |] printfn "%A" array array |> Array.sum |> printfn "Π‘Ρ€Π΅Π΄Π½Π΅Π΅ арифмСтичСскоС элСмСнтов списка: %A" let ar = array |> Array.sum |> fun a -> a / 20 printfn "sum: %A" ar //let ar2 = array |> Array.sum //let ar3 = ar2 //let br = ar3 / n //let br = ar //printfn "Π‘Ρ€Π΅Π΄Π½Π΅Π΅ арифмСтичСскоС элСмСнтов списка 2: %A" br Console.ReadLine() |> ignore 

Why in the end is the arithmetic mean zero? If during debugging correctly calculates both the number n and the sum of the elements of the array itself?

  • one
    Did you use integer division? - VladD
  • The problem was just the fact that I divided int into int - mayst
  • You may be interested - recently opened the chat on F # , so if you have any questions, feel free to ask - user227049

2 answers 2

F # divides int by int entirely. Cast to float or double and get 0.5:

 let ar = array |> Array.sum |> float |> fun a -> a / 20.0 

Or use the /. operator /. from a set of Type-inference friendly division and multiplication .

    In F# there is a special function Array.average to find the average value. It has a restriction on the use only for elements of those types that support DivideByInt . The int type does not apply to these, so you cannot use the function. But you can use the Array.averageBy function

     let avr = array |> Array.averageBy float 

    The condition states:

    To form a list in the range from -n to n according to the following pattern:

    Your code:

     let array = [| for i in 0 .. n -> if i%2=0 then ((ni)* -1) else ni |] 

    specifies only half the sequence. If you want a sequence from [-n; n], then you can use this approach:

     let array = [| for i in 0 .. 2 .. 2 * n - 1 do yield -(n - i) yield n - i - 1 yield n |] 

    In this case, the average number of elements will be 0 , which is quite obvious.