Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
mathieu-lemay opened this issue Jul 19, 2024 · 2 comments
Closed
Labels
bug Something isn't working

Comments

@mathieu-lemay
Copy link
Contributor

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):

  • OS: macOS 14.5
  • go version output: go version go1.22.5 darwin/arm64

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
}
@mathieu-lemay mathieu-lemay added the bug Something isn't working label Jul 19, 2024
@jaswdr
Copy link
Owner

jaswdr commented Jul 22, 2024

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

@mathieu-lemay
Copy link
Contributor Author

Fixed by #178

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants