Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double as close to 0 as possible?

I need a value as close to 0 as possible. I need to be able to divide through this value, but it should be effectively 0.

Does Java provide an easy way of generating a double with only the least significant bit set? Or do I have to calculate it myself?


//EDIT: A little background information, because someone requested it. I know that my soultion is not a particularly clean one, but here you are:

I am writing a program for homework. It calculates the resistance of a circuit consisting of multiple resistors in parallel and serial circuits.

It is a 2nd year programming class. Our teacher still designs classes for us, we need to implement them according to his design.

Parallel circuits involve calculation of 1/*resistance*, therefore my program prohibits creation of resistors with 0 Ohm. Physics tells you that this is impossible anyway (you have just a tiny little resistance in every metal).

However, the example circuit we should use to test the program contains a 0 Ohm resistor. It is placed in a serial circuit, but resistors do not know where they are (the teacher designed it that way), so I cannot change my program to allow resistors with 0 Ohm resistance in serial circuits only.

Two solutions:

  1. Allow 0 Ohm resistors in any case - if division by 0 occurs, well, bad luck
  2. Set the resistor not to 0, but to a resistance one can neglect.

Both are not very good. The first one seemed not too good to me, and neither did the second, but I had to decide.

It was just a random choice that threw up the problem. I could not let go without solving it, so switching to the first one was not an option anymore ;-)

like image 790
fNek Avatar asked Jan 28 '14 15:01

fNek


1 Answers

Use Double.MIN_VALUE:

A constant holding the smallest positive nonzero value of type double, 2-1074. It is equal to the hexadecimal floating-point literal 0x0.0000000000001P-1022 and also equal to Double.longBitsToDouble(0x1L).

like image 50
Rohit Jain Avatar answered Sep 19 '22 22:09

Rohit Jain