Rounding Algorithm Half-Up, Down, Even, Odd

June 18, 2009

Rounding algorithms have very common use in calculation to display result with desired decimal places. Most common forms, are used in programming is Up or Ceil and Down or Floor. Most crucial part come up with Half. There are a lot of variation depending on Negative and Positive number. This post is dedicated to these variations.

Half Up:
For positive number you have the simple one. If the last digit after the point is grater than or equals to 5 then you will take the next digit.

Number->Applying Half Up
2 -> 2
2.1 -> 2
2.2 -> 2
2.3 -> 2
2.4 -> 2
2.5 -> 3
2.6 -> 3
2.7 -> 3
2.8 -> 3
2.9 -> 3
3 -> 3

Half Up Symmetric:
For negative number Half Up rounding algorithm divides into two part. One is Symmetric respect to zero and another one is Asymmetric respect to 0. Symmetric respect to 0 means its characteristic is same as the positive number except the sign, thus -2.5 will be noted as -3 (as 2.5 noted as 3 in half up algorithm for positive number). Its absolute value is symmetric respect to point 0.

Number->Applying Half Up Symmetric
-2 -> -2
-2.1 -> -2
-2.2 -> -2
-2.3 -> -2
-2.4 -> -2
-2.5 -> -3
-2.6 -> -3
-2.7 -> -3
-2.8 -> -3
-2.9 -> -3
-3 -> -3

Half Up Asymmetric:
Here the real half up applies. -2.5 will be up so it will be -2 (coz its negative). Rest of the things are same.

Number->Applying Half Up Asymmetric
-2 -> -2
-2.1 -> -2
-2.2 -> -2
-2.3 -> -2
-2.4 -> -2
-2.5 -> -2
-2.6 -> -3
-2.7 -> -3
-2.8 -> -3
-2.9 -> -3
-3 -> -3

Half Down:
For positive number if the last digit after point is less than or equal to 5 then it will stick to previous number.

Number->Applying Half Down
2 -> 2
2.1 -> 2
2.2 -> 2
2.3 -> 2
2.4 -> 2
2.5 -> 2
2.6 -> 3
2.7 -> 3
2.8 -> 3
2.9 -> 3
3 -> 3

Half Down Symmetric:
This is for negative numbers. Here the absolute value is same as the Half down for positive number, thus, -2.5 will be -2.

Number->Applying Half Down Symmetric
-2 -> -2
-2.1 -> -2
-2.2 -> -2
-2.3 -> -2
-2.4 -> -2
-2.5 -> -2
-2.6 -> -3
-2.7 -> -3
-2.8 -> -3
-2.9 -> -3
-3 -> -3

Half Down Asymmetric:
If less than or equals to .5, go down to previoud negative number

Number->Applying Half Down Symmetric
-2 -> -2
-2.1 -> -2
-2.2 -> -2
-2.3 -> -2
-2.4 -> -2
-2.5 -> -3
-2.6 -> -3
-2.7 -> -3
-2.8 -> -3
-2.9 -> -3
-3 -> -3

Half Even:
Well known as bankers rounding algorithm. Most of the financial software use it for calculation in ledger. If the last digit is equal 5 then that will be rounded to nearest even number. Digit less than 5 will be down and greater than 5 will be up. There is no distinction for negative and positive number. For example 2.5 will be 2(even). 3.5 will be 4(even)

Number->Applying Half Even
2 -> 2
2.1 -> 2
2.2 -> 2
2.3 -> 2
2.4 -> 2
2.5 -> 2
2.6 -> 3
2.7 -> 3
2.8 -> 3
2.9 -> 3
3 -> 3
3.1 -> 3
3.2 -> 3
3.3 -> 3
3.4 -> 3
3.5 -> 4
3.6 -> 4
3.7 -> 4
3.8 -> 4
3.9 -> 4
4 -> 4

Half Odd:
Simply the opposite of Half Even. Here 2.5 will be 3(odd). 3.5 will be 3(Odd)

Number->Applying Half Odd
2 -> 2
2.1 -> 2
2.2 -> 2
2.3 -> 2
2.4 -> 2
2.5 -> 3
2.6 -> 3
2.7 -> 3
2.8 -> 3
2.9 -> 3
3 -> 3
3.1 -> 3
3.2 -> 3
3.3 -> 3
3.4 -> 3
3.5 -> 3
3.6 -> 4
3.7 -> 4
3.8 -> 4
3.9 -> 4
4 -> 4

By Md. Shahjalal


Allow fields of list of Beans in SimpleFormController of Spring MVC

June 10, 2009

ServletRequestDataBinder of Spring framework is used  to protect unwanted biding of attributes of Bean in SimpleFormController of Spring MVC. You can define precisely which fields will be bind to the bean in view layer. Programmer used to do it by overriding the createBinder() method. Explicitly define the allowed fields in a String array and set in (servletRequestDataBinder.)setAllowedFields(allowedFields) method. Now think of a bean where you have a list of another bean. For example a bean of Course contains multiple sections.

class Bean {
.....
int id
String courseName;
List sections;
.....
}
class Section {
int id
String facultyName;
}

You have override the createBinder() method and code as follows

protected ServletRequestDataBinder createBinder(HttpServletRequest request, Object o) throws Exception {
ServletRequestDataBinder servletRequestDataBinder = super.createBinder(request, o);
String[] allowedFields = {"courseName"};
return servletRequestDataBinder.setAllowedFields(allowedFields);
}

Now how to allow your preferred fields of section with it? Well the solution is really simple. Bean elements of a list are represent by a special format in spring. And the format is:

listName[listIndex].fieldName

So you can make your required binder by following code:

protected ServletRequestDataBinder createBinder(HttpServletRequest request, Object o) throws Exception {
ServletRequestDataBinder servletRequestDataBinder = super.createBinder(request, o);
String[] allowedFields = {"courseName", "sections[0].facultyName"};//for 1 section
return servletRequestDataBinder.setAllowedFields(allowedFields);
}

You can run a loop for number of sections and make a list and eventually covert the list into an array list for allowing preferred fields.

By: Md. Shahjalal


Multiple session or multi-window problem and solution where same form opened in multiple tab or window extended from SimpleFormController of Spring MVC

June 4, 2009

My previous entry about multi-window or Multiple session shows how we can maintain different session for a same form extended from SimpleFormController of Spring MVC, used by multiple class. Now what about a Form extended from SimpleFormController of Spring MVC opened in different tab or window? A new one will always replace the bean from the session after showing form on showForm() method.

showForm() method of SimpleFormController save the bean in session if setSessionForm(true) for that form just before redering the view. Session works like a HashMap. It saves the bean by a name and this name retrived by calling getFormSessionAttributeName() method. Which is simply the class name(with prefix of package name) + “.Form.command”. So the new bean always replaces the old one in session.

Problem: For example you have a Patient data entry form extended from SimpleFormController of Spring MVC. You want to update two patiend information in two different tab of your browser. You open one form fill up all data and before submit you open another form in another tab. Now the bean in the session will be replaces by this new patient’s information. Now you submit this and get back to previous tab and submit that. onSubmit() method retrive the bean from the session which is the information of the second tab. So you will get incompatible data.

Solution: Soluation is same as the previous entry. You have to override  getFormSessionAttributeName(HttpServletRequest request) method and make sure two name in the session is different. Find a unique identity for two different form. It can be patient id assigned by Hospital or clinic or database index of the patient in storage device. Choosing database index has a problem. Before you submit a new form, you do not know the index so this key is 0(=zero) for a new form.

You can generate a patient id for a new form and keep it as a request attribute and modify session attribute name by overriding getFormSessionAttributeName(HttpServletRequest request) like following code

//to set inrequest:
request.setAttribute("patientId", patientId);
//in getFormSessionAttributeName(HttpServletRequest request) method
@Override
protected String getFormSessionAttributeName(HttpServletRequest request) {
String patientId = (String)request.getAttribute("patientId");
return super.getFormSessionAttributeName()+"."+patientId;
}

So when controller calls getFormSessionAttributeName() it got different session attribute name for two different name and overwrite of bean is prohibited.

by Md. Shahjalal


Encapsulation is not just data hiding

May 18, 2009

Most of people consider encapsulation feature of object oriented programming as data hiding. But Encapsulation stands for few more features. Suppose we have a Vehicle registration software. Which has following properties,

  • Vehicle has a engine/chesis number
  • Vehicle may have door
  • Vehicle have wheels
  • Vehicle can be different type: Bus, Car, Bike

Suppose we have a Abstract Vehicle

Class public abstract class Vahicle {
public abstract String getChesisNumber();
public int getNumberOfDoor() {}
public abstract int getNumberOfWheel();
}

Now Bus, Car, Bike extend Vehicle

public abstract class Bus extends Vehicle {
public int getNumberOfDoor() {}
}public abstract class Car extends Vehicle
{
public int getNumberOfDoor() {
return 4;
}
public abstract class Bike extends Vehicle { }

Now a Car can be a Private car or Taxi so

public PrivateCar extends Car {
public String getChesisNumber() {
return "CN354656565";
}
public int getNumberOfWheel(){
return 4;
}
}

Suppose we have a special type of Air Conditioned Taxi named ClassicTaxi

public ClassicTaxi {
public String getEngineNumber(){
return "CN35465655498";
}
public int getTotalNumberOfWheel(){
return 4;
}
}

Only the Taxi know about this

public Taxi extends Car {
private ClassicTaxi ct;
public String getChesisNumber(){
return ct.getEngineNumber();
}
public int getNumberOfWheel(){
return ct.getTotalNumberOfWheel();
}

Now you can notice the different levels of Encapsulation in this example.

  1. Encapsulation of Data: Bus, Bike and PrivateCar and Taxi are encapsulation from everything
  2. Encapsulation of Type: Client of Vehicle do not know about Bus, Car and Bike
  3. Encapsulation of Method: getNumberOfDoor() of Bus and Car are hidden from all
  4. Encapsulation of Object: Only Taxi is aware abot Classic Taxi

So as we can see. Its not only bounded to the hiding data but also hiding type, method as well as object too. There is land mark theory described in the book of Gang of Four(GOF) “Consider what should be variable in your design. This approach is the opposite of focusing on the causes of redesign. Instead of considering what might force a change to a design, consider what you want to be able to change without redesign. The focus here is on encapsulating the concept that varies, a theme of many design patterns.”(Ref 1) The Book of Shalloway define this simply as “Find what varies and encapsulate it.” (Ref 2).

References:

1. Design Pattern: Elements of Reusable Object-Oriented Software
2. Design Pattern Explained: A new perspective on Object Oriented Design

By: Md. Shahjalal


Faster Calculation : Part 1 : n^2 for 9, 3 and 5

May 7, 2009

We often heard about some gifted genius who can calculate without calculator. Some of them even faster than the result come out from a manual computer. Are they use some trick? or they are simply genius to multiply or divide those big numbers. Most of them claim they do all they calculation fast. I have no idea. May be they are gifted. The common format of the number we use is decimal. 10 digit from 0-9. Some of these number contains interesting characteristics in multiplication. Here is some calculations for n^2 where n = any number of sequence of a specific digit.

1. Chemistry on n=9

9*9 = 81
99*99 = 9801
999*999 = 998001
9999*9999 = 99980001
99999*99999 = 9999800001

No notice carefully. Number of 9 increased to calculate the power of 2, number of 9 and 0 increases at 1st position and between 8 and 1. You can go as much as you need without really calculating these.

2. Shaded pyramid of n=3
9
1089
110889
11108889
1111088889
111110888889
11111108888889
1111111088888889
111111110888888889

Simply same as 9 :)

3. No lets move into little tough game :) think of n=5

25
3025
308025
30858025
3086358025
308641358025
30864191358025
3086419691358025
308641974691358025
30864197524691358025
3086419753024691358025
308641975308024691358025
30864197530858024691358025
3086419753086358024691358025
308641975308641358024691358025
30864197530864191358024691358025
3086419753086419691358024691358025
308641975308641974691358024691358025
30864197530864197524691358024691358025

Yes i know you are stuck. Have a fresh breath.  Now look from the  very  2nd row. What extra thing you have from the 1st one? 30. Now look at every row right in the middle you have 2 digits extra every time. And these are 30 80 58 63 41 91 69 74 52 30 80  58. Wait a second :) Can you see something? yes its a loop. Begin with 30 and ends with 52. Thats all you have to add on every row. Nothing else to calculate this.

By: Md. Shahjalal