P
P
PRAIT2019-08-11 03:12:14
Java
PRAIT, 2019-08-11 03:12:14

Java how to calculate square root?

Hello smart people! Thanks for dropping by, and thanks to those who replied!
I need to calculate the square root using Java and there seems to be a solution, but I don’t understand what’s wrong here?
Option number 1

public class Dunamicinicilization {

  public static void main(String[] args) {
    double a = -4;
    
    // динамическая инициализация переменной c
    double c = Math.sqrt (a * a);
    System.out.println(c);
  }
}

This option produces 4.0
Second option
doulbe x = 9;
double y = Math.sqrt(x);
System.out.print(y);

Displays NaN
But in the first and second options it should be -4, right? What am I doing wrong? Explain, please.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexander, 2019-08-11
@NeiroNx

Do not carry nonsense, everything is normally extracted:5d4f7e8096c9d339803926.png

M
markbugatti, 2020-05-13
@markbugatti

The fact is that the square root of a negative number cannot be found.
If, for example, we square -2, then (-2) * (-2) = 4. A minus times a minus gives a plus. Accordingly, the root of 4 can be found: it will be either 2 or -2. In mathematics, they often write √4=±2. Since -2 squared and +2 squared \u003d 4.
And you can’t find the square root from a negative number.
If the root is not looking for a square, but of any other degree, then the following rule works here: You can find the root of an unpaired degree from a minus number, but you cannot find the root of a paired degree from a minus number.
For example: ∛-27 =- 3, ∜(-16)=Error, ∜16=±2

K
Kolya K, 2019-08-11
@Kolyagrozamorey

Before you start learning Java, you need to learn mathematics and then such questions will not arise.

S
Sergey Bezrukov, 2019-09-30
@gena88zotov

See how the square root calculation works here https://calcok.com/nauka-i-ucheba/8.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question