Creating an array of numbers that add up to 1 with given length

gun*_*tan 1 python algorithm numpy scipy

I'm trying to use different weights for my model and I need those weights add up to 1 like this;

def func(length):
    return ['a list of numbers add up to 1 with given length']
Run Code Online (Sandbox Code Playgroud)

func(4) returns [0.1, 0.2, 0.3, 0.4]

The numbers should be linearly spaced and they should not start from 0. Is there any way to achieve this with numpy or scipy?

App*_*ish 5

This can be done quite simply using numpy arrays:

def func(length):
    linArr = np.arange(1, length+1)
    return linArr/sum(x)
Run Code Online (Sandbox Code Playgroud)

First we create an array of length length ranging from 1 to length. Then we normalize the sum.

Thanks to Paul Panzer for pointing out that the efficiency of this function can be improved by using Gauss's formula for the sum of the first n integers:

def func(length):
    linArr = np.arange(1, length+1)
    arrSum = length * (length+1) // 2
    return linArr/arrSum
Run Code Online (Sandbox Code Playgroud)