Ask Your Question
2

formatting numbers in sagetex

asked 2012-11-08 14:57:18 +0100

naegling gravatar image

If I put (for example) \sage{1.2*V} in my .tex file the resulting pdf has

1.20000000000000 V

How can I tell it to not print trailing zeros?

Thanks.

edit retag flag offensive close merge delete

4 Answers

Sort by ยป oldest newest most voted
3

answered 2012-11-09 11:04:53 +0100

Jason Grout gravatar image

updated 2012-11-09 11:07:28 +0100

I worked on a ticket to help with this a while ago: http://trac.sagemath.org/sage_trac/ti...

You can see a comment from Carl Witty that gives a good approach: (I really like his option 1). Basically, it allows for setting options for printing any numbers from a RealField.

For an individual number, you're looking for the skip_zeroes argument to str:

sage: a=1.2
sage: a
1.20000000000000
sage: a.str(skip_zeroes=True)
'1.2'

Alternatively, this is the default behavior for python floats (as opposed to Sage floating point numbers), so if you either turn off the preparser or use python floats, you'll get what you want:

sage: float(1.2)*x
1.2*x
sage: preparser(False)
sage: 1.2*x
1.2*x
edit flag offensive delete link more
1

answered 2015-03-10 23:50:08 +0100

Kevin Cox gravatar image

I find that the easiest way to to convert to a python floating point before printing.

float(24/5)          #-> 4.8
"%.4f" % float(26/3) #-> 8.6667
edit flag offensive delete link more
1

answered 2012-11-09 13:37:01 +0100

Depending on the type of calculations, you might be able to work in RDF, for example, or in `RealField(23)`, replacing 23 by whatever number gives you the desired precision.

edit flag offensive delete link more

Comments

In addition to the nicer output without trailing zeros, using RDF will usually make everything faster.

slelievre gravatar imageslelievre ( 2015-03-11 12:17:53 +0100 )edit
0

answered 2012-11-08 16:36:06 +0100

Dirk Danckaert gravatar image

Try \sage{(1.2).n(6)*V}. The .n(6) command specifies the number of significant bits used to represent the number. As a rule of thumb 3 bits ~ 1 digit.

edit flag offensive delete link more

Comments

Yes, that would work for this example, but what in the general case \sage{x} where x is the result of some calculation I can't just call .n(6) on the result because there are non-numeric variables. Does this mean that I should call .n on all the floating point numbers as they enter into the calculation?

naegling gravatar imagenaegling ( 2012-11-08 17:29:21 +0100 )edit

I think so, yes. In general you know from the start if the result will be numeric or not. And most of the time you also know the precision you are aiming at.

Dirk Danckaert gravatar imageDirk Danckaert ( 2012-11-09 07:05:25 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2012-11-08 14:57:18 +0100

Seen: 2,861 times

Last updated: Mar 10 '15