-1

for example:

6+1.2=6*1.2
5+1.25=5*1.25

I want to try to write a program to search the result like search prime number:

public class Test{
    public static void main(String[] args){
        float x=-1.0f;
        float d=0.0001f;
        for(float y=-10;y<10;y=y+d){
            if(x+y-x*y>=-d && x+y-x*y<=d){
                System.out.println(y);
            }
        }
    }
}

but the program has some problem:

  1. It can search result from -10 to 10 only, because search between Float.MIN_VALUE and Float.MAX_VALUE is too slow
  2. I know 9+1.125=9*1.125, but even I set each increment is 0.0001, the program cannot find any result
  3. sometimes the program print multiple result around the real result

Is there any other faster method or better algorithm to find the result?

timrau
  • 22,578
  • 4
  • 51
  • 64
ggrr
  • 7,737
  • 5
  • 31
  • 53
  • 6
    [Algebraically?](http://www.wolframalpha.com/input/?i=Solve%5Bx%2By%3D%3Dx*y%2Cy%5D&dataset=) – David Eisenstat Jul 06 '15 at 02:05
  • to know why it didn't work with float or double, you must read [Is floating point math broken?](http://stackoverflow.com/q/588004/995714), [What Every Computer Scientist Should Know About Floating-Point Arithmetic ](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). Because there's no binary floating-poin value that's exactly 1.2, 7.2 or 0.0001 – phuclv Jul 06 '15 at 03:08
  • you also should do some research about floating point numbers and the meaning of `MIN_VALUE` and `MAX_VALUE` and specially Epsilon. In Floating Point Math, there is a threshold where `x + y == x` if `y`<<`x` This threshold depends on difference of the magnitude of both values – vlad_tepesch Jul 06 '15 at 11:34

1 Answers1

5

Algebraically:

y = x / (x - 1)

It will be significantly faster than trying to iterate your way towards an answer.

As mentioned below, don't forget to catch x = 0

Wheeldog
  • 178
  • 8