Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to autogenerate array in kotlin similar to numpy?

Tags:

kotlin

hello let me do a demonstration in python about what I want to achieve in kotlin:

np.linspace(start = 0, stop = 100, num = 5)

This results:

-------------------------
|0 | 25 | 50 | 75 | 100 |
-------------------------

Now in Kotlin how can I get the same result? Is there a similar library?

like image 607
royer Avatar asked Dec 21 '25 21:12

royer


2 Answers

This should work exactly like linspace (not handling cases when num is 0 or 1):

fun linspace(start: Int, stop: Int, num: Int) = (start..stop step (stop - start) / (num - 1)).toList()

It makes use of the rangestart..stop (a range in kotlin is inclusive) and the function step lets us define how far the steps in this ranges should be.

EDIT
As @forpas suggested in the comments the step should be calculated using (stop - start) and not only stop. Using stop alone would only work if the start was 0.

@Alexey Romanov correctly said that unless you explicitly need a List as return type you should return the IntProgression (it does not hold all the elements in memory like a list does) since its also Iterable.

Thank you both for your input!

like image 163
Rene Ferrari Avatar answered Dec 24 '25 12:12

Rene Ferrari


Not exactly the same, but it generates an array with 5 integers, multiples of 25 starting from 0:

val array = Array(5) { it * 25  }

the result is:

[0, 25, 50, 75, 100]

You can create a function simulating what you need:

fun linspace(start: Int, stop: Int, num: Int) = Array(num) { start + it * ((stop - start) / (num - 1)) }
like image 26
forpas Avatar answered Dec 24 '25 12:12

forpas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!