# Building our own mutation function

We have seen before how just by mutation and selecting the top best candidates that are closer to the goal, we have some kind learning by evolutionary effect. In theory people call this genetic algorithm. So in this blog we will be building our own mutation function that will mutate values and give it to us. So here it is:

```
function mutate(value, mutation_percent_range, number_of_mutations)
output = []
for i in 1:number_of_mutations
mutation = value * (1 + (rand(mutation_percent_range) / 100))
push!(output, mutation)
end
output
end
```

Let’s see how it works. First we have an empty function:

```
function mutate()
end
```

We need to mutate a value here, so let’s have it:

```
function mutate(value)
end
```

We need say how much we need to mutate an value, lets exploit the property of `Range`

in Julia. So if we want to mutate it by +/- 10%, we say -10:10, so let that be our second argument named `mutation_percent_range`

:

```
function mutate(value, mutation_percent_range)
end
```

So we need to pick a random value from `mutation_percent_range`

:

```
function mutate(value, mutation_percent_range)
rand(mutation_percent_range)
end
```

divide it by hundred since it’s a percentage:

```
function mutate(value, mutation_percent_range)
rand(mutation_percent_range) / 100
end
```

multiply add it to mutation value:

```
function mutate(value, mutation_percent_range)
value * (1 + (rand(mutation_percent_range) / 100))
end
```

and this will give a mutated value. But we want lot of mutations for the next generation as many of them could be rejected and only few would survive, so let’s add a third parameter called `number_of_mutations`

:

```
function mutate(value, mutation_percent_range, number_of_mutations)
value * (1 + (rand(mutation_percent_range) / 100))
end
```

Now, for `number of mutations`

times we need to mutate:

```
function mutate(value, mutation_percent_range, number_of_mutations)
for i in 1:number_of_mutations
mutation = value * (1 + (rand(mutation_percent_range) / 100))
end
end
```

Collect it so that it won’t be lost, for that let’s use an `Array`

called `output`

to capture it and return it as shown:

```
function mutate(value, mutation_percent_range, number_of_mutations)
output = []
for i in 1:number_of_mutations
mutation = value * (1 + (rand(mutation_percent_range) / 100))
push!(output, mutation)
end
output
end
```

So our mutation function is ready. Let’s test it out

```
mutate(100, -10:10, 10)
```

Output:

```
10-element Array{Any,1}:
92.0
100.0
93.0
99.0
108.0
92.0
109.00000000000001
106.0
91.0
110.00000000000001
```

And it works! You can get the Jupyter notebook file for this blog here https://gitlab.com/data-science-with-julia/code/-/blob/master/mutate.ipynb.