## Snippets in category Mathematics

### Form changing color

Windows Forms tutorial showing how to create form with button and how to register an event handler. When the button is clicked, the form changes its background color.

46 people like this

**Posted**: 4 years ago by Tomas Petricek### Support slicing operator

The snippet shows how to support slicing in a type. Slicing allows you to get for example a 2D sub-matrix of a matrix and is implemented by adding GetSlice member.

46 people like this

**Posted**: 4 years ago by Tomas Petricek### Array shuffle

Shuffle an array

47 people like this

**Posted**: 4 years ago by Laurent### Random Type with a few modifications

The modified Random type is built on top of System.Random type. It has a member Seed which returns a seed and NextFloat has the same overloads as NextInt (Next in System.Random). The members should further support units of measure.

17 people like this

**Posted**: 4 years ago by Oldrich Svec### Distance between two 3D segments

The function segmentSegment takes 2 segments (starting and ending points) and computes the shortest distance between them. The function returns a starting and ending point of the shortest segment between the two segments. The function uses a triple type but can be easily rewritten to work with any other type (vector etc).

30 people like this

**Posted**: 4 years ago by Oldrich Svec### Sequence Random Permutation

A generic function that randomly permutes the elements of a sequence.

43 people like this

**Posted**: 4 years ago by Taha Hachana### inline pow

LanguagePrimitives help create inline functions

41 people like this

**Posted**: 4 years ago by Dmitri Pavlenkov### Function to get all possible combinations

Function to get all possible combinations of list items. There are some Euler problems (like 77 & 78) to get total amounts. But e.g. for some card game implementations you will need the real items.

44 people like this

**Posted**: 4 years ago by Tuomas Hietanen### Millerâ€“Rabin primality test

Millerâ€“Rabin primality test is an algorithm which determines whether a given number is probable prime. For more information go to http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test

33 people like this

**Posted**: 4 years ago by Cesar Mendoza### All combinations of list elements

For a given list, find all possible combinations of elements of the list (not just k-combinations). The result is a list of lists with each element representing one combination. Order of elements is not taken into account.

26 people like this

**Posted**: 4 years ago by Alexander Rautenberg### Cartesian product of n lists

Cartesian product of a variable number of lists. Input is a list of lists of which the cartesian product is to be constructed; output is a list that contains the elements of the product set, as lists.

11 people like this

**Posted**: 4 years ago by Alexander Rautenberg### Pascal's Triangle

Returns the pascal triangle in a 2D list . This snippet computes rows translating the 'visual' method taught at school into Lists and the usage of map2 function. It takes almost 5 seconds to compute 5000 rows.

19 people like this

**Posted**: 4 years ago by Horacio Nuñez### A Lazy fixed-point combinator

x = f(x) encoded in F#

22 people like this

**Posted**: 4 years ago by Nick Palladinos### Primitive Pythagorean triples

Primitive Pythagorean triples generator. It uses an Algorithm found on Wolfram MathWorld and the F# PowerPack matrix library.

46 people like this

**Posted**: 4 years ago by Cesar Mendoza### Gaussian Random Sequence

Normalized Random sequence generator conforming to the user supplied mean and sigma utilizing a "seed factory" instead of the default time of day. The Gaussian sequence is based on the central limit theory, averages together the flat distribution from the random generator built into .NET. Two examples of using normalRand are given to create infinite sequences of white and brown(ian) noise.

44 people like this

**Posted**: 4 years ago by Tony Lee### Graham scal algorithm for finding the convex hull of a sequence of 2D points

finds the points lying on the convex hull of the given set of points and returns those points in clockwise direction, starting at the point with minimum y-value Remarks: it's a more or less direct implementation of the algorithm named after Ronald Graham that is explained on http://en.wikipedia.org/wiki/Graham_scan you can switch the definition Point for a proper type of your liking - e.g. System.Drawing.Point

39 people like this

**Posted**: 4 years ago by Carsten König### QR-decomoposition of a square-matrix using the Gram-Schmidt method

shows a simple implementation of a vector and matrix type together with a QR-decomposition using the Gram-Schmidt method. The algorithms themselfes are rather easy but I think the implementation of the types and the computations using recursive techniques might be interessting

3 people like this

**Posted**: 4 years ago by Carsten König### How to write a financial contract

Implements the theory from 'How to write a financial contract' by S.L Peyton Jones and J-M Eber

9 people like this

**Posted**: 4 years ago by Ademar Gonzalez### Combinatorial functions

Here is my F# take on some combinatorial functions from the book "Introduction to Functional Programming" by Richard Bird and Philip Wadler.

5 people like this

**Posted**: 4 years ago by Cesar Mendoza### Permutations

computes the list of all permutations of a list for example the permutations of [1;2;3] will be [1;2;3]; [1;3;2]; [2;1;3]; [2;3;1]; [3;1;2]; [3;2;1]

2 people like this

**Posted**: 4 years ago by Carsten König### Very Fast Permutations

I spent a lot of time this week profiling different permutation functions from various places on the internet. The following was by far the fastest:

8 people like this

**Posted**: 4 years ago by Rick Minerich### Computation Builder for Cartesian Products

Sample framework for computing Cartesian products using a computation builder.

8 people like this

**Posted**: 4 years ago by TechNeilogy### Moving Average

Given a period and a sequence of values, calculates the moving average of the input. E.g., given a period of 4 and a sequence of { 2.0, 8.0, 12.0, 10.0, 6.0, 4.0, 14.0 }, the result of this function is { 8.0, 9.0, 8.0, 8.5 }.

8 people like this

**Posted**: 4 years ago by Brett V. Forsgren### Calculating the angle between the hour and minute hand

This is a response to a Google interview question that someone encountered. A friend of mine was recently hired there and I've heard some thrilling stories of their interview process. So every now and then, I plan to code up a response to one of the hoards of interview questions they have.

0 people like this

**Posted**: 4 years ago by Antwan "A-Dubb" Wimberly### Calculating the angle between the hour and minute hand redux

This snippet introduces a further subtlety into the previous posting, whereby the intra-hour movement of the hour hand is captured.

0 people like this

**Posted**: 4 years ago by HP### Permutation and Combination

Permutation and Combination using ListBuilder.

9 people like this

**Posted**: 4 years ago by zecl### Prime numbers - Sieve of Eratosthenes

Basic prime number generator

1 people like this

**Posted**: 4 years ago by d95danb### Prime testing

Simple check if a number is prime. See also http://fssnip.net/2w.

1 people like this

**Posted**: 4 years ago by d95danb### RSK algorithm

Implements a bijective mapping between permutations and pairs of standard Young tableaux, both having the same shape. http://en.wikipedia.org/wiki/Robinson%E2%80%93Schensted_correspondence

4 people like this

**Posted**: 3 years ago by Ademar Gonzalez### Compute CC.Net build statistics

Written against CruiseControl.NET v1.5. Queries a CruiseControl.NET server for a project list and then computes min, max, average, and standard deviation of the build durations based on the statistics.csv CC.NET maintains.

3 people like this

**Posted**: 3 years ago by Matt Wilson### Calculate PI number

PI number calculation based on the wikipedia page(http://en.wikipedia.org/wiki/Pi#cite_note-59). I used Newton's , Machine's and Ramanujan's formula. (updated: line 21: Seq.take => Seq.truncate)

3 people like this

**Posted**: 3 years ago by nagat01### A fast sieve of Eratosthenes

A prime Eratosthenes' sieve, using a bit array and sieving only odd composites to conserve memory and keep things fast.

3 people like this

**Posted**: 3 years ago by Arjen Kopinga### Folding over prime factors

Let's have some fun with higher order functions and instead of folding over a list, fold over the prime factors of a number. It can be optimized further by dividing out real primes instead of numbers of the form 6k+/-1, but it's not embarrassingly slow.

1 people like this

**Posted**: 3 years ago by Arjen Kopinga### Random Subset

A function that takes a random subset from a seq<'T>.

0 people like this

**Posted**: 3 years ago by Taha Hachana### XNA's Vector3 with units of measure

A vector type with units of measure built on top of XNA's Vector3. Not complete, the point is mainly to show how to use generic units of measure to adapt an existing type.

9 people like this

**Posted**: 3 years ago by Johann Deneux### Discrete Fréchet Distance

Compute the Discrete Fréchet Distance between two arrays (which may be of different lengths). Based on the 1994 algorithm by Thomas Eiter and Heikki Mannila. Not extensively tested, so use at your peril! (This version with some small fixes.)

0 people like this

**Posted**: 3 years ago by Kit Eason

### Ninety-Nine F# Problems - Problems 31 - 41 - Arithmetic]

These are F# solutions of Ninety-Nine Haskell Problems which are themselves translations of Ninety-Nine Lisp Problems and Ninety-Nine Prolog Problems. The solutions are hidden so you can try to solve them yourself.

3 people like this

**Posted**: 3 years ago by Cesar Mendoza### Matrix

Matrix

2 people like this

**Posted**: 3 years ago by Matrix### A simple sieve

A simple implementation for the sieve of Eratosthenes.

3 people like this

**Posted**: 3 years ago by Gab_km### SIngle Life Annuity

A single life annuity function in F# including supporting functions such as probability of survival, pure endowment and discounted interest rate calculation.

0 people like this

**Posted**: 3 years ago by Kevin Roche### Single Life Annuity

A single life annuity function in F# including supporting functions such as probability of survival, pure endowment and discounted interest rate calculation. I've gone for (what I believe to be) a more functional approach than the previous version. I've cobbled together a sort of computation expression type to facilitate transforming the AgeVector. The code below contains test data and sample tests so that you can see how it should be used. If you have any queries or advice about this please contact me on twitter @CdeRoiste . Have fun!

6 people like this

**Posted**: 3 years ago by Kevin Roche### Bayesian Monte Carlo of Let's Make a Deal

This code illustrates Bayes' Theorem in action on the Let's Make a Deal problem (aka Monty Hall Problem), which several authors have used to illustrate Bayes' Theorem. (It's easy to search the internet for further explanation.) Run with the audit option to audit up to the first 100 games. Running without audit is faster and can simulate a couple billion games.

4 people like this

**Posted**: 3 years ago by Jack Fox### Monotone Chain Convex Hull Algorithm

Andrew's Monotone Chain Convex Hull algorithm: given points in 2 dimensions, determine their convex hull by constructing the upper and lower hull.

5 people like this

**Posted**: 3 years ago by Mathias Brandewinder### Simple Markov chains

Small example illustrating how to use Arrays and Sequences to simulate simple Markov chain and evaluate their stationary distribution.

3 people like this

**Posted**: 3 years ago by Mathias Brandewinder### Calculate PI using Monte Carlo

Simple walkthrough that demonstrates how to estimate the value of PI using Monte Carlo simulation. A few holes need to be filled in and then you can run & parallelize the sample!

4 people like this

**Posted**: 3 years ago by Tomas Petricek### Checking for perfect squares

An implementation of John D. Cook's algorithm for fast-finding perfect squares: http://www.johndcook.com/blog/2008/11/17/fast-way-to-test-whether-a-number-is-a-square/

1 people like this

**Posted**: 3 years ago by Kit Eason### fast Fourier transforms (FFT)

Naive "school-book" implimentation.

13 people like this

**Posted**: 3 years ago by Kaspar### Slicing for Math.Net vectors and matrices

This snippet adds the 'GetSlice' operation to Math.Net vector and matrix types. This makes it possible to get sub-vectors and sub-matrices using the convenient syntax (For vectors 'vect.[start .. end]` or 'vect.[start ..]' and for matrices 'mat.[r1 .. r2, c1 .. c2]' and similar).

8 people like this

**Posted**: 2 years ago by Tomas Petricek### Square root for integral types

Square root for integral types

5 people like this

**Posted**: 2 years ago by ildjarn### Density of sparse matrix product

A quick exploration of the rather useless question "how does the density of the product of 2 sparse matrices look like?"

0 people like this

**Posted**: 2 years ago by Mathias Brandewinder### Density of sparse matrix product

A quick exploration of the rather useless question "how does the density of the product of 2 sparse matrices look like?"

0 people like this

**Posted**: 2 years ago by Mathias Brandewinder### Primes

Generates the Prime Number Sequence.

1 people like this

**Posted**: 2 years ago by AdamSpeight2008### Joint Life Annuity

This Joint Life Annuity calculation relies on the objects and functions defined in Single Life Annuity. A joint life annuity calculates the present value of an annuity from current age to death of a member and another life (spouse). The implementation below uses the AgeVectorBuilder from the Single Life Annuity snippet in two examples: The first defines a simple Joint Life Annuity that assumes no age difference between the two lives. The second assumes an N year age difference. The samples both rely on a male mortality table (PMA92 (C=2003)) and a female mortality table (PFA92 (C=2003)) which are extracts of publicly available mortality tables (http://www.actuaries.org.uk/research-and-resources/documents/pma92-pensioners-males-amounts).

1 people like this

**Posted**: 2 years ago by Kevin Roche### Combinations n choose k

given an array n generates all lists with k choices from n

5 people like this

**Posted**: 2 years ago by isaiah perumalla### Inverse error function (float)

let erfinv x = let mutable p = 0.0 let mutable w = -log((1.0-x)*(1.0+x)) // corrected sign if w < 5.000000 then w <- w - 2.500000 p <- 2.81022636e-08 p <- 3.43273939e-07 + p*w p <- -3.5233877e-06 + p*w p <- -4.39150654e-06 + p*w p <- 0.00021858087 + p*w p <- -0.00125372503 + p*w p <- -0.00417768164 + p*w p <- 0.246640727 + p*w p <- 1.50140941 + p*w else w <- sqrt w - 3.000000 p <- -0.000200214257 p <- 0.000100950558 + p*w p <- 0.00134934322 + p*w p <- -0.00367342844 + p*w p <- 0.00573950773 + p*w p <- -0.0076224613 + p*w p <- 0.00943887047 + p*w p <- 1.00167406 + p*w p <- 2.83297682 + p*w p*x

2 people like this

**Posted**: 2 years ago by Clever people### DivRem Operator

Defines the operator /% as DivRem for int, int64 and bigint.

5 people like this

**Posted**: 2 years ago by Diego Frata### Calculate PI using Monte Carlo

Estimate the value of PI using a Monte Carlo simulation.

4 people like this

**Posted**: 2 years ago by Phillip Trelford### Linear Regression Gradient Descent

Liner Regression with no reglarization

### DBSCAN

Density-based spatial clustering of applications with noise (DBSCAN) is a data clustering algorithm. For more information see http://en.wikipedia.org/wiki/DBSCAN. The implementation is based on the pseudocode in the article and the following C# code http://www.c-sharpcorner.com/uploadfile/b942f9/implementing-the-dbscan-algorithm-using-C-Sharp/ The implementation is not very functional but does the job. Added pwd by ignorance, the password is "fssnip" (without quotes)

1 people like this

**Posted**: 2 years ago by Samuel Bosch### Great circle distance

Compute the great circle distance of 2 points

3 people like this

**Posted**: 2 years ago by Samuel Bosch### Evaluating random arithemtic expressions

Generate a random expression and evaluate it

1 people like this

**Posted**: 2 years ago by devshorts### Convert integers to positive values

Convert negative and positive integers to a positive value by using an overlap and interleave scheme (more info: http://en.wikipedia.org/wiki/Golomb_coding).

1 people like this

**Posted**: 1 years ago by Samuel Bosch### Azimuthal equidistant projection

Simple and a more optimized implementation of the azimuthal equidistant projection. Input is expected in degrees.

3 people like this

**Posted**: 1 years ago by Samuel Bosch### Azimuthal equidistant projection with measures

Simple version of the azimuthal equidistant projection (see also http://fssnip.net/lA) but with measures. This avoids mixing of degrees and radians and longitudes/x and latitudes/y

2 people like this

**Posted**: 1 years ago by Samuel Bosch### matrix-inv.fsx

calcula la matriz inversa

0 people like this

**Posted**: 1 years ago by ivpadim### Simple KMeans clustering in 2D

I needed a crude k-means (http://en.wikipedia.org/wiki/K-means_clustering) clustering method for a one off test of something, and decided to try to do in F# for learning purposes

1 people like this

**Posted**: 1 years ago by @BrockSamsonUK### Generate simple linear equation systems

Generates simple systems of linear equations, suitable for being solved by someone who's just started learning about them. Change the ranges to make them suitable for solving without a calculator.

1 people like this

**Posted**: 1 years ago by Anonymous### Array Shuffle

Shuffling array using Seq.fold

3 people like this

**Posted**: 1 years ago by Karlkim Suwanmongkol### Generic number literal

A generic numeral G. It allows writing functions for arbitrary numeric type. The transformation is an efficient one, because it is implemented explicitly for every type. It combines the type classes technique of FsControl (https://github.com/gmpl/FsControl and http://nut-cracker.azurewebsites.net/typeclasses-for-fsharp) with numeric literals. But FsControl is removed to completely avoid unnecessary function calls.

4 people like this

**Posted**: 1 years ago by Daniel Fabian (@iceypoi)### Similar string Markov chain

Generates strings that are similar to the input, as measured by the probability of a symbol depending on preceding symbols. (Markov chain) The order, which defines how many preceding symbols to look at before placing another, is variable.

0 people like this

**Posted**: 10 months ago by Vandroiy### Rational type for units of measure

A more idiomatic definition of a Rational type with custom operators.

1 people like this

**Posted**: 9 months ago by Tomas Petricek### Fourth order Runge-Kutta ODE solver

This is a simple and direct implementation of fourth order runge-kutta ordinary differential equation solver algorithm. In the main function three use cases are shown.

1 people like this

**Posted**: 8 months ago by Antonio Prestes García