jaswdr / faker

:rocket: Ultimate fake data generator for Go with zero dependencies
https://pkg.go.dev/github.com/jaswdr/faker
MIT License
549 stars 59 forks source link

[BUG] Unexpected behavior from the Float* and RandomFloat functions #177

Open mathieu-lemay opened 2 months ago

mathieu-lemay commented 2 months ago

Describe the bug The maxDecimals argument in those functions is not doing what I expect it to do. The name implies that it will generate a float with that number of decimals, but what it actually does is generating a number between 1 and n and using that as a decimal. This means that if I use maxDecimals=2, all the floats I get will have .1 or .2 as the decimal value, instead of a decimal value between .00 and .99.

Note that because the floats are first generated as strings and then parsed, we also end up with some floating point errors.

This might be intended behaviour, in that case I think it should be documented.

To Reproduce

package main

import (
    "fmt"
    "math"

    "github.com/jaswdr/faker/v2"
)

func main() {
    fake := faker.New()

    for i:=0; i<10; i++ {
        fmt.Println(fake.RandomFloat(2, 0, 100))
    }
}

Sample output from that code:

38.20000076293945
83.0999984741211
88.19999694824219
72.0999984741211
29.100000381469727
20.200000762939453
72.0999984741211
3.200000047683716
92.19999694824219
31.100000381469727

Note that the decimal part all have float rounding issues and are all basically .1 or .2

Expected behavior I expected to get values looking this, with 2 decimals

82.75
34.91
29.43
90.05
93.29
89.34
34.15
12.39
19.47
32.8

Desktop (please complete the following information):

Additional context Here is a sample algorithm that behaves like I expect. This is the algorithm I've used to generate the expected values above

func (f Faker) RandomFloat(maxDecimals, min, max int) float64 {
    n := float64(f.IntBetween(min, max-1))
    if maxDecimals < 1 {
        return n
    }

    p := int(math.Pow10(maxDecimals))
    d := float64(f.IntBetween(0, p)) / float64(p)

    return n+d
}
jaswdr commented 1 month ago

@mathieu-lemay thank you for the report, I'll take a look ASAP