Skip to content

Weird decimal values #195

Open
Open
@wesleywilian

Description

@wesleywilian

Hey there,

Nice project @ericlagergren

I was wondering if I'm missing something

This code here

func TestDecimal(t *testing.T) {
	var ctx decimal.Context
	ctx.Precision = 128

	// dt = 1 / 60
	dt := new(decimal.Big)
	ctx.Quo(dt, decimal.New(1, 0), decimal.New(60, 0))

	// acceleration = 0.2
	acceleration := new(decimal.Big).SetFloat64(0.2)

	// speed = 0
	speed := new(decimal.Big).SetFloat64(0.0)

	// Run for 10 ticks
	for i := 1; i <= 10; i++ {
		deltaSpeed := new(decimal.Big)
		ctx.Mul(deltaSpeed, dt, acceleration) // deltaSpeed = dt * acceleration
		ctx.Add(speed, speed, deltaSpeed)     // speed += deltaSpeed

		// log
		fmt.Printf("Tick %2d: speed = %v\n", i, speed.String())
	}
}

Results on this output

Tick  1: speed = 0.0033333333333333335183705041041927567372719446818033854166666666666666666666666666666666666666666666666666666666666666666666666667
Tick  2: speed = 0.0066666666666666670367410082083855134745438893636067708333333333333333333333333333333333333333333333333333333333333333333333333334
Tick  3: speed = 0.010000000000000000555111512312578270211815834045410156250000000000000000000000000000000000000000000000000000000000000000000000000
Tick  4: speed = 0.013333333333333334073482016416771026949087778727213541666666666666666666666666666666666666666666666666666666666666666666666666667
Tick  5: speed = 0.016666666666666667591852520520963783686359723409016927083333333333333333333333333333333333333333333333333333333333333333333333334
Tick  6: speed = 0.020000000000000001110223024625156540423631668090820312500000000000000000000000000000000000000000000000000000000000000000000000001
Tick  7: speed = 0.023333333333333334628593528729349297160903612772623697916666666666666666666666666666666666666666666666666666666666666666666666668
Tick  8: speed = 0.026666666666666668146964032833542053898175557454427083333333333333333333333333333333333333333333333333333333333333333333333333335
Tick  9: speed = 0.030000000000000001665334536937734810635447502136230468750000000000000000000000000000000000000000000000000000000000000000000000002
Tick 10: speed = 0.033333333333333335183705041041927567372719446818033854166666666666666666666666666666666666666666666666666666666666666666666666669

But the expected should repeat the numbers and avoid those numbers like 51837050410419275673727194468180338541... on tick 1

Any insights?

Thank you

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions