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

浮点数相乘 #15

Open
GoldThree opened this issue Nov 22, 2021 · 3 comments
Open

浮点数相乘 #15

GoldThree opened this issue Nov 22, 2021 · 3 comments
Labels
bug Something isn't working

Comments

@GoldThree
Copy link

0.7*360=251.99999999999997

@GoldThree
Copy link
Author

这种好像没有做处理 🧐

@dengsgo dengsgo added the bug Something isn't working label Nov 22, 2021
@jimyag
Copy link

jimyag commented Sep 7, 2022

可以使用 https://github.com/shopspring/decimal 做处理

package main

import (
	"fmt"

	"github.com/dengsgo/math-engine/engine"
	"github.com/shopspring/decimal"
)

func main() {
	s := "0.7*360"
	// call top level function
	r, err := engine.ParseAndExec(s)
	if err != nil {
		fmt.Println(err)
	}
	p, err := decimal.NewFromString(fmt.Sprintf("%f", r))
	if err != nil {
		panic(err)
	}

	fmt.Println(p) //252
}

本来想用 decimal 处理浮点数精度的问题,但是发现会损失精度

// Top level function
// Analytical expression and execution
// err is not nil if an error occurs (including arithmetic runtime errors)
func ParseAndExec(s string) (r float64, err error) {
	toks, err := Parse(s)
	if err != nil {
		return 0, err
	}
	ast := NewAST(toks, s)
	if ast.Err != nil {
		return 0, ast.Err
	}
	ar := ast.ParseExpression()
	if ast.Err != nil {
		return 0, ast.Err
	}
	defer func() {
		if e := recover(); e != nil {
			err = e.(error)
		}
	}()
	res, err := decimal.NewFromString(fmt.Sprintf("%f", ExprASTResult(ar)))
	if err != nil {
		return 0, err
	}
	r, _ = res.Float64()
	return r, err
}

=== RUN TestParseAndExecSimple
util_test.go:85: {3^4.5 140.29611541307906} ParseAndExec: 140.296115
util_test.go:85: {3.5^4.5 280.7412308013823} ParseAndExec: 280.741231
util_test.go:85: {pi 3.141592653589793} ParseAndExec: 3.141593
--- FAIL: TestParseAndExecSimple (0.00s)

FAIL

@jacktrane
Copy link

应该是要你保留多少个小数吧?这个看起来是被四舍五入了

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

4 participants