Home > database >  math.sqrt gives me incorrect result (double)
math.sqrt gives me incorrect result (double)

Time:11-26

I am writing a program that prints 100 random coordinates within a circle. The circle has the radius 10 and its center is located at (0,0). However, some of the coordinates y:value is incorrectly calculated when I'm using: y = Math.sqrt(100 -x^2) The result is like off... Why is that ? (See picture) For positive y:values, they get too big sometimes and its because of the math.sqrt calculation with doubles.

package RKap14;

import ZindansMethods.ZindanRandom;

public class Dot {
    public double x;
    public double y;
    
    public static void main(String[] arg)throws Exception {
        
        //Create the array with null fields?
        Coord[] c;
        //Decide how many fields
        c = new Coord[100];
        //Create an object of class Coord in each slot of the array
        for(int i = 0; i<c.length; i  ) {
            c[i] = new Coord();
        }
            //Assign random coordinates for each field x & y
            for(int i = 0; i<c.length; i  ) {
                c[i].x = ZindanRandom.randomized(-10,10); 
                    //Since sometimes Java calculates wrong and gives numbers above 10 and below -10...
                    while(c[i].x > 10 || c[i].x < -10)
                    c[i].x = ZindanRandom.randomized(-10,10); 
                c[i].y = ZindanRandom.randomized(-Math.sqrt(100-c[i].x*c[i].x), Math.sqrt(100-c[i].x*c[i].x));
            }
        
        
            //Print out the coordinates in form: (x,y),(x1,y1)...(x99,y99)
        for (int i = 0; i<c.length; i  ) {
            System.out.print("("   c[i].x   ","   c[i].y   ")"   ",");
        }

    }
}

class Coord {
    double x;
    double y;
}

The random method I am using:

//Gives random number a to b. For example -10 <= x <= 10
public static double randomized (double a, double b) {
        return (a-1 Math.random()*Math.abs(b-a 1) 1);       
    }

I don't know what to try. I tried doing this program with a trigonometric approach but I'd rather understand why the calculator is doing its job wrongfully. Are there too many decimals? Can I do something about it ?

Circle test

CodePudding user response:

your random function is generating numbers outside the given range

for example if you substitute the values into your equation and and use 1 as the value returned from Math.random() you will get 101.

Try the following random function instead:

public static double randomized(double min, double max)
  return Math.random() * (max - min)   min;
}
  • Related