Skip to content

Redwall MUCK Site

Sections
Personal tools
You are here: Home » Members » Riverdale's Home » Code Examples » Teaching » Decimal Division
« December 2008 »
Su Mo Tu We Th Fr Sa
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31      
 

Decimal Division

An illustration of how to return a decimal value when dividing, followed by an invitation for someone to finish what I started.

Decimal Math in MPI

To fudge basic decimal operations in MPI, simply multiply all the relevant values by 10x10^n, where n is the desired level of precision, and then put the decimal point n+n characters from the end of the returned number. If you're dividing, only multiply the larger value by 10x10^n, and place the decimal point n characters from the end

Example: I want the answer to 10 / 3 to three decimal places:

                @mpi {div:{mult:10,1000},3}  --> 3333

Obviously 10 / 3 is not 3333, so we need to change this output to something that appears correct. To do this, we use some string manipulation techniques:

                @mpi {with:n,{div:{mult:10,1000},3}, {if:{gt:{strlen:{&n}},3},\
                     {midstr:{&n},1,-4},0}.{midstr:{&n},-3,-1}}  --> 3.333

So let's take those concepts and make them reusable:

                @set me=_msgmacs/fdiv:{with:n,{div:{mult:{:1},1{left:,{:3},0}},{:2}},
                {if:{gt:{strlen:{&n}},{:3}},{midstr:{&n},1,-{add:{:3},1}},0.{midstr:{&n},-{:3},-1}}}

Use {fdiv} like this: {fdiv:first number, second number, precision}.

In the code, I used {left} to add the appropriate number of zeroes to the 1. I may have forgotten if there is a more appropriate way of repeating way of repeating a string an arbitrary number of times, if one exists.

Since {midstr} has the annoying habit of being crappy, you must check to make sure that you don't grab -3 (third from last character) when you want a non-existent -4: hence the {if:{gt:{strlen... bit.

I hope someone else will carry this idea to completion, since this macro is mostly useless in isolation. A set of macros, capable of adding, multiplication, and so on, is more useful.

Created by Riverdale
Last modified 2008-08-22 03:46 PM
 

Powered by Plone

This site conforms to the following standards: