Nan java как исправить

whatick

1 / 1 / 0

Регистрация: 18.11.2012

Сообщений: 19

1

18.11.2012, 20:58. Показов 5568. Ответов 10

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Всем привет

В коде в некоторых ответах (значение х равный дробному отрицательному числу, т.е. -3,5; -2,5; -1,5; -0,5; ) выдает nan, а остальные значения считает, помогите разобраться

Java
1
2
3
4
5
6
7
8
    System.out.println ( "nПрограмма выводит на экран таблицу значений функции у = 2х^-5х-8 в диапазоне от -4 до 4. Шаг изменения аргумента 0,5." );
    double y;
    for ( double i = -4; i <= 4; i += 0.5 )
    {
        double x = i;
        y = 2 * Math.pow ( x, -5 * x ) - 8;
//      System.out.println ( y );
        System.out.printf ("n%5.8f", y );

Выводит такие значения

2.199023255544E12
NaN
-2.8697822E7
NaN
2040.0
NaN
-10.0
NaN
-6.0
3.3137084989847594
-6.0
-7.904424725780751
-7.998046875
-7.999978778313857
-7.999999860616561
-7.999999999397663
-7.999999999998181



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

18.11.2012, 20:58

10

14 / 13 / 5

Регистрация: 04.10.2012

Сообщений: 29

19.11.2012, 01:29

2

Для примера возьмем первый NaN. Он получается при возведении в степень таким образомтаким образом:
х = -3.5
Math.pow(-3.5, -5 * (-3.5) ) = Math.pow( -3.5, -17.5) = Math.pow( -3.5, 35 / 2)

Сначала отрицательное число (-3.5) возводится в нечетную степень, что дает нам отрицательное число, из которого мы пытаемся извлечь корень. Квадратный корень из отрицательного числа не действительный, потому и не может быть помещен в тип double, который возвращает функция Math.pow. Остальные NaN‘ы получаются аналогично.



0



1 / 1 / 0

Регистрация: 18.11.2012

Сообщений: 19

19.11.2012, 02:45

 [ТС]

3

т.е. этот пример правильно не посчитается? или можно изменить код, что на выходе цифры были?



0



Эксперт Java

4088 / 3822 / 745

Регистрация: 18.05.2010

Сообщений: 9,331

Записей в блоге: 11

19.11.2012, 07:40

4

Цитата
Сообщение от whatick
Посмотреть сообщение

т.е. этот пример правильно не посчитается? или можно изменить код, что на выходе цифры были?

Странный вопрос, как вы собираетесь извлекать корень из -3.5?



0



SpamBot

14 / 13 / 5

Регистрация: 04.10.2012

Сообщений: 29

19.11.2012, 13:30

5

Там где NaN, значение функции посчитать нельзя, поэтому на графике это будут так называемые «выколотые» точки, где значение функция не имеет значения. Поэтому при вычислении уместно сделать проверку:

Java
1
2
3
4
if(Double.valueOf(y).isNaN())
  System.out.println("Значение функции не определено");
else
  System.out.printf ("n%5.8f", y );



0



1 / 1 / 0

Регистрация: 18.11.2012

Сообщений: 19

19.11.2012, 14:02

 [ТС]

6

Цитата
Сообщение от turbanoff
Посмотреть сообщение

Странный вопрос, как вы собираетесь извлекать корень из -3.5?

я сначала в mathcad считал, так он выводит значение. Я с С++ перешел на java, так вот подумал, может в последней есть что подобное…
Название: !!!!!!!!!!!!1.JPG
Просмотров: 235

Размер: 2.4 Кб



0



1 / 1 / 0

Регистрация: 18.11.2012

Сообщений: 19

19.11.2012, 14:40

 [ТС]

7

я понимаю, что степерь 1/2= корень и что корень из отрицательного числа не считается, но вот в mathcad посчиталось.



0



2000 / 1427 / 92

Регистрация: 25.11.2010

Сообщений: 3,611

19.11.2012, 14:44

8

Цитата
Сообщение от whatick
Посмотреть сообщение

я понимаю, что степерь 1/2= корень и что корень из отрицательного числа не считается, но вот в mathcad посчиталось.

И какое значение mathcad выдает для https://www.cyberforum.ru/cgi-bin/latex.cgi?{-2}^{-0.5}?



0



1 / 1 / 0

Регистрация: 18.11.2012

Сообщений: 19

19.11.2012, 14:59

 [ТС]

9

Цитата
Сообщение от whatick
Посмотреть сообщение

я сначала в mathcad считал, так он выводит значение. Я с С++ перешел на java, так вот подумал, может в последней есть что подобное…
Вложение 202621

Цитата
Сообщение от Skipy
Посмотреть сообщение

И какое значение mathcad выдает для https://www.cyberforum.ru/cgi-bin/latex.cgi?{-2}^{-0.5}?

странно все это…

Название: !!!!!!!!!!!!!2.JPG
Просмотров: 232

Размер: 1.4 Кб



0



1 / 1 / 0

Регистрация: 18.11.2012

Сообщений: 19

19.11.2012, 15:02

 [ТС]

10

он видно работает как с комплексными просто )



0



Эксперт Java

4088 / 3822 / 745

Регистрация: 18.05.2010

Сообщений: 9,331

Записей в блоге: 11

19.11.2012, 15:10

11

Цитата
Сообщение от whatick
Посмотреть сообщение

странно все это…

Он вам выводит https://www.cyberforum.ru/cgi-bin/latex.cgi?-({2}^{-0.5})



0



Нужно сделать программу, которая выводит результат вычисления выражения в консоль. Проблема в том, что результат выводится корректно, если присвоить значения переменным в коде программы. Но если ввести их с клавиатуры, то выводит nan. Код на Java.
Как исправить ошибку и сделать две такие же программы на C и C++ ?

    package Formula;
    import static java.lang.Math.pow;
    import java.util.Scanner;




    public class My_Program {
    public static void main(String[] args) {

        double m, a, res, s1, e, l1, s2, mod1, mod2, l2;
        System.out.println("Введите целое число х:");
        Scanner in= new Scanner (System.in);
        int x = in.nextInt();
        System.out.println("Введите целое число d:");
        int d = in.nextInt();
        System.out.println("Введите дробное число a. Целую и дробную часть разделите запятой:");
        a = in.nextDouble();
        System.out.println("Введите дробное число u. Целую и дробную часть разделите запятой:");
        m = in.nextDouble();

        s1= Math.pow(Math.sin( pow(d,3)),2);
        e=Math.exp(Math.abs(a-Math.tan(x)));
        mod1=Math.abs((1-s1)/(1.5+e));

        l1=pow(Math.log(pow(a,2)),3);
        s2=pow(Math.sin(d),2);
        mod2=Math.abs((m-l1)/(1+s2));
        l2=pow(Math.log(mod2)/Math.log(3),2);

        res=Math.acos (pow( mod1,0.3333)+Math.sqrt(2.7+l2));


        System.out.print("Входные данные rn");
        System.out.print("============== rn");
        System.out.printf("a =%.1f",a);
        System.out.print( "rn");
        System.out.printf("d = %d ",d);
        System.out.print( "rn");
        System.out.printf("x = %d",x);
        System.out.print( "rn");
        System.out.printf("U=%f",m);
        System.out.print("rn");
        System.out.print("Результат:rn");
        System.out.print("==============");
        System.out.print( "rn");
        System.out.printf("B= %f",res);
    }
}

Ok so i am bulding this application that calculates 3 input boxes. i am getting a NaN when doing some calculations with 0 values.
here is the main.xml

<?xml version="1.0" encoding="utf-8"?>


<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:id="@+id/ScrollView01" >




<AbsoluteLayout android:orientation="vertical"
    android:layout_width="fill_parent" android:layout_height="fill_parent">



    <EditText android:id="@+id/InputNumber01"
        android:numeric="integer|decimal" android:imeOptions="actionNext"
        android:textStyle="bold" android:hint="Service Call"
        android:layout_x="5dip" android:layout_y="5px" android:layout_height="55dip"
        android:textSize="20dip" android:layout_width="195dip"
        android:selectAllOnFocus="true" android:inputType="numberDecimal"/>



    <EditText android:id="@+id/InputNumber02"
        android:numeric="integer|decimal" android:inputType="numberDecimal"
        android:textStyle="bold" android:hint="Parts" android:layout_x="5dip"
        android:layout_y="90px" android:layout_height="55dip"
        android:textSize="20dip" android:layout_width="195dip"
        android:selectAllOnFocus="true" android:imeOptions="actionNext"/>



    <EditText android:id="@+id/InputNumber03" android:numeric="integer|decimal"
        android:inputType="numberDecimal" android:textStyle="bold"
        android:hint="Labor" android:layout_x="5dip" android:layout_y="175px"
        android:layout_height="55dip" android:textSize="20dip"
        android:layout_width="195dip" android:selectAllOnFocus="true"
        android:imeOptions="actionDone"/>

    <Button android:text="Calculate" android:id="@+id/actionButton"

        android:textStyle="bold" android:layout_height="50dip"
        android:layout_width="fill_parent" android:layout_y="300px"
        android:textSize="15dip" />


    <TextView android:id="@+id/TextResult" android:layout_height="wrap_content"
        android:numeric="integer|decimal" android:textStyle="bold"
        android:layout_width="85dip" android:layout_x="225dip"
        android:layout_y="175dip" android:gravity="left" android:textSize="18dip"
        android:textColor="#1d9ee2" />



    <TextView android:layout_height="wrap_content" android:id="@+id/TextView04"
        android:text="Total:" android:textStyle="bold" android:gravity="right"
        android:layout_width="55dip" android:layout_y="175dip"
        android:layout_x="165dip" android:textSize="18dip" />

    <TextView android:layout_height="wrap_content" android:id="@+id/TextView05"
        android:text="Total Labor:" android:layout_y="260dip"
        android:layout_width="95dip" android:layout_x="5dip" android:gravity="right" />

    <TextView android:text="@+id/TotalLabor"
        android:layout_height="wrap_content" android:layout_width="wrap_content"
        android:id="@+id/TotalLabor" android:layout_y="260dip"
        android:layout_x="110dip" />

    <TextView android:layout_height="wrap_content" android:id="@+id/TextView06"
        android:layout_x="5dip" android:text="Total Services:"
        android:layout_y="280dip" android:layout_width="95dip"
        android:gravity="right" />

    <TextView android:layout_height="wrap_content"
        android:layout_width="wrap_content" android:id="@+id/TotalServices"
        android:text="@+id/TotalServices" android:layout_y="280dip"
        android:layout_x="110dip" />

    <TextView android:id="@+id/TextView07" android:text="SC Tax %:"
        android:layout_y="300dip" android:layout_height="wrap_content"
        android:layout_x="5dip" android:layout_width="95dip" android:gravity="right" />

    <TextView android:text="@+id/TextView08"
        android:layout_height="wrap_content" android:layout_width="wrap_content"
        android:id="@+id/SCTaxPercent" android:layout_y="300dip"
        android:layout_x="110dip" />

    <TextView android:layout_height="wrap_content" android:id="@+id/TextView08"
        android:text="Sales Tax:" android:textStyle="bold" android:layout_y="175dip"
        android:layout_x="5dip" android:textSize="18dip"
        android:layout_width="wrap_content" android:gravity="right" />

    <TextView android:layout_height="wrap_content" android:id="@+id/SalesTax"
        android:textStyle="bold" android:numeric="integer|decimal"
        android:layout_y="175dip" android:gravity="left"
        android:layout_width="65dip" android:textSize="18dip"
        android:layout_x="100dip" />

    <TextView android:layout_height="wrap_content" android:id="@+id/TextView09"
        android:text="SC Taxable:" android:layout_y="320dip"
        android:layout_x="5dip" android:layout_width="95dip" android:gravity="right" />

    <TextView android:layout_height="wrap_content" android:text="@+id/TextView10"
        android:layout_width="wrap_content" android:id="@+id/ScTaxable"
        android:layout_y="320dip" android:layout_x="110dip" />

    <TextView android:layout_height="wrap_content" android:id="@+id/TextView10"
        android:text="Taxable:" android:layout_y="340dip"
        android:layout_width="95dip" android:layout_x="5dip" android:gravity="right" />

    <TextView android:layout_height="wrap_content" android:text="@+id/TextView11"
        android:layout_width="wrap_content" android:id="@+id/Taxable"
        android:layout_y="340dip" android:layout_x="110dip" />

    <EditText android:layout_height="wrap_content" android:text="9.50"
        android:layout_width="90dip" android:id="@+id/SalesTaxValue"
        android:layout_x="5dip" android:layout_y="430dip" android:numeric="integer|decimal"
        android:selectAllOnFocus="true" />

    <TextView android:layout_height="wrap_content" android:id="@+id/TextView01"
        android:layout_width="wrap_content" android:layout_x="5dip"
        android:text="Sales Tax Value:" android:layout_y="407dip" />
</AbsoluteLayout>
</ScrollView>

and this is the calculator.java

package com.Eddie.TaxCalculator;

import java.text.NumberFormat;

import com.Eddie.TaxCalculator.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Calculator extends Activity {
    private Button calculateButton;
    private EditText inputField01;
    private EditText inputField02;
    private EditText inputField03;
    private EditText salesTaxValue;
    private double serviceCall;
    private double parts;
    private double labor;
    private double salestaxvalue;


String zero ="0";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        calculateButton = (Button) findViewById(R.id.actionButton);
        calculateButton.setOnClickListener(doSomethingNow);
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

        }

    private OnClickListener doSomethingNow = new OnClickListener() {
        public void onClick(View arg0) {
            inputField01 = (EditText) findViewById(R.id.InputNumber01);
            inputField02 = (EditText) findViewById(R.id.InputNumber02);
            inputField03 = (EditText) findViewById(R.id.InputNumber03);
            salesTaxValue = (EditText) findViewById(R.id.SalesTaxValue);


            if (inputField01.getText().toString().length()==0)
                    {
                       inputField01.setText(zero);
                    Toast toast = Toast.makeText(getApplicationContext(), 
                            "Service Call TextBox was empty.",
                            Toast.LENGTH_LONG);
                    toast.show();
                    }       
            if(inputField02.getText().toString().length()==0)
                    {
                       inputField02.setText(zero);
                    Toast toast = Toast.makeText(getApplicationContext(), 
                            "Parts TextBox was empty.",
                            Toast.LENGTH_LONG);
                    toast.show();
                    }   
            if(inputField03.getText().toString().length()==0)
                    {
                       inputField03.setText(zero);
                    Toast toast = Toast.makeText(getApplicationContext(), 
                            "Labor TextBox was empty.",
                            Toast.LENGTH_LONG);
                    toast.show();
                    }
            //service Call is 0
            if (inputField01.getText().toString().equals("0"))
            {
            Toast toast = Toast.makeText(getApplicationContext(), 
                    "Service Call TextBox value is 0.",
                    Toast.LENGTH_SHORT);
            //toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
            toast.show();
            }       
            //Parts is 0
                if (inputField02.getText().toString().equals("0"))
            {
               //inputField01.setText("10");
            Toast toast = Toast.makeText(getApplicationContext(), 
                    "Parts TextBox value is 0.",
                    Toast.LENGTH_SHORT);
            toast.show();
            }   
            //Labor is 0
            if (inputField03.getText().toString().equals("0"))
            {
               //inputField01.setText("10");
            Toast toast = Toast.makeText(getApplicationContext(), 
                    "Labor TextBox value is 0.",
                    Toast.LENGTH_SHORT);
            toast.show();
            }   


            serviceCall = Double.parseDouble(inputField01.getText().toString());
            parts = Double.parseDouble(inputField02.getText().toString());
            labor = Double.parseDouble(inputField03.getText().toString());
            salestaxvalue = Double.parseDouble(salesTaxValue.getText().toString());

            NumberFormat numberFormat = NumberFormat.getInstance();
            numberFormat.setMaximumFractionDigits(2);            
            numberFormat.setGroupingUsed(false); 



            TextView totalLabor = (TextView)findViewById(R.id.TotalLabor);
            Double totalLaborResults =  serviceCall +  labor;
            String totalLaborCalcInt = numberFormat.format(totalLaborResults).toString();
            totalLabor.setText (totalLaborCalcInt);

            TextView totalServices = (TextView)findViewById(R.id.TotalServices);
            Double totalServicesResults = (parts + labor);
            String totalServicesCalcInt = numberFormat.format(totalServicesResults);
            totalServices.setText (totalServicesCalcInt);


            TextView servicecallTaxpercent = (TextView)findViewById(R.id.SCTaxPercent);
            Double scTaxPercentResults =  (parts / totalServicesResults);
            String serviceCallPercentCalcInt =  numberFormat.format(scTaxPercentResults).toString();
            servicecallTaxpercent.setText (serviceCallPercentCalcInt);

            TextView scTaxable = (TextView)findViewById(R.id.ScTaxable);
            Double scTaxableResults = (serviceCall * scTaxPercentResults);
            String serviceCallTaxableCalcInt =numberFormat.format (scTaxableResults).toString();
            scTaxable.setText (serviceCallTaxableCalcInt);

            TextView taxable = (TextView)findViewById(R.id.Taxable);
            Double taxableResults = (parts + scTaxableResults);             
            String taxableCalcInt =numberFormat.format (taxableResults).toString();
            taxable.setText (taxableCalcInt);

            TextView salesTax = (TextView)findViewById(R.id.SalesTax);
            Double salesTaxResults = (taxableResults * salestaxvalue) /100;
            String salesTaxCalcInt = numberFormat.format (salesTaxResults).toString();
            salesTax.setText (salesTaxCalcInt);

            TextView textResult = (TextView)findViewById(R.id.Total);
            Double additionResults = (salesTaxResults + parts+ serviceCall +  labor);
            String TotalCalcInt = numberFormat.format(additionResults).toString();
            textResult.setText (TotalCalcInt);

                }

    };

};

when entering a number in input 1 (service Call) and zeros in the two other inputs i get a NaN Total.

if All input Boxes are zero value i also get a NaN total, NaN sale Tax, NaN scTax % textview (sc is short of Service Call)
NaN scTaxable, NaN taxable.

could anyone help me find this but i’ve been trying for two weeks now.
pls help.

программа вроде работает, но выводит NaN

package com.javarush.task.task05.task0507;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/*
Среднее арифметическое
*/

public class Solution {
public static void main(String[] args) throws Exception {
//напишите тут ваш код
while (true){
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
double a = Double.parseDouble(reader.readLine());
double b=0;
int c=0;
if (a==-1) {
double d=b/c;
System.out.println(d);
break;
}
else {
b+=a;
c++;
}
}
}
}

Этот веб-сайт использует данные cookie, чтобы настроить персонально под вас работу сервиса. Используя веб-сайт, вы даете согласие на применение данных cookie. Больше подробностей — в нашем Пользовательском соглашении.

We learn something everyday. We don’t always realise it, but we do. Sometimes the thing you learn isn’t new at all, but something you sort of knew
but never really thought about too much.

I recently learned that my understanding of what causes a NaN value in Java’s double was wrong.

The story

I was working on an integration project and received a bug report on one of my services. The report said that my service is returning an HTTP code ‘500’ for a specific input message.

During my investigation I found the cause of the exception was an unexpected value returned from a down stream service. It was a SOAP service which returned something like the following in its XML response:

<SomeNumberField type="number">NaN</SomeNumberField>

I was a bit surprised to see the NaN there since I would expect them to either leave the field off or set it to null if they don’t have a value. This looked like a calculation bug since we all know that, in Java and C# at least, dividing a double with 0 results in a NaN. (Spoiler: It doesn’t)

However, this got me thinking and I tried to remember what I know about doubleand NaN. This resulted in an embarrisingly deep spiral down the rabbit hole.

NaN

Well if you think about it NaN is kind of like a number in this case, even though NaN means Not-a-Number. It exists to enable calculations with indeterminate results to be represented as a “number” in the set of valid double values. Without NaN you could get completely wrong results or you’ll get an exception, which isn’t ideal either. NaN is defined, same as Infinity, to be part of the set of valid doubles.

System.out.println(Double.isNaN(Double.NaN)); //true
System.out.println(Double.POSITIVE_INFINITY == Double.POSITIVE_INFINITY); //true
System.out.println(Double.NEGATIVE_INFINITY == Double.NEGATIVE_INFINITY); //true

I played around with double a bit and I thought to share it in a post, because I think the various edge cases of double are interesting.

I started with the following experiment:

//Lets make a NaN!
double NaN = 5.0/0;
System.out.println("NaN: " + NaN);

>> NaN: Infinity

Wait. What?

Turns out that I have lived with this misconception about what happens when you divide a double by zero. I seriously expected that a double divided by 0 is NaN. Well it turns out I was wrong. You get:

POSITIVE_INFINITY

double infinity = 5.0/0;
System.out.println((infinity == Double.POSITIVE_INFINITY)); //true

I can sort of rationalise that the answer could be infinity because you are dividing something largish with something much much smaller. In fact, dividing it by nothing so you could argue the result of that should be infitely large. Although, mathematically this does not make any sense. x/0 is undefined since there is no number that you can multiply with 0 to get back to x again. (for x <> 0)

Anyway lets play with NaN a bit.

double NaN = Double.NaN;
System.out.println("NaN: " + NaN); //NaN: NaN

System.out.println((NaN + 10)); //(NaN + 10): NaN
System.out.println((NaN - 10)); //(NaN - 10): NaN
System.out.println((NaN - NaN)); //NaN - NaN: NaN
System.out.println((NaN / 0));     //NaN / 0: NaN
System.out.println((NaN * 0));     //NaN * 0: NaN

Well no surprises here. Once a NaN always a NaN.

I used Double.NaN above to be sure I have a NaN but if you want to make one yourself then calculating the square root of a negative number is an easy way:

System.out.println((Math.sqrt(-1))); //NaN

Max and Min value

Before we get to infinity let take a quick look at Double.MAX_VALUE and Double.MIN_VALUE. These are special constants defined on Double which you can use to check if a number is at the maximum of what a double can represent. If a number is equal to Double.MAX_VALUE it means that it is about to overflow into Double.POSITIVE_INFINITY. The same goes for Double.MIN_VALUE except that it will overflow to Double.NEGATIVE_INFINITY.

Something to note about double is that it can represent ridiculously large numbers using a measly 64 bits. The maximum value is larger than 1.7*10^308 !

System.out.println("Double.MAX_VALUE is large! : " + (Double.MAX_VALUE == 1.7976931348623157 * Math.pow(10,308)));

> Double.MAX_VALUE is large! : true

It can represent these large numbers because it encodes numbers as a small real number multiplied by some exponent. See the IEEE spec

Let’s see what it takes to make Double.MAX_VALUE overflow to infinity.

double max = Double.MAX_VALUE;

System.out.println((max == (max + 1))); //true
System.out.println((max == (max + 1000))); //true
System.out.println("EVEN...");
System.out.println((max == (max + Math.pow(10,291)))); //true

System.out.println("HOWEVER...");
System.out.println((max == (max + Math.pow(10,292)))); //false
System.out.println((max + Math.pow(10,292))); //Infinity

This ability to represent seriously large numbers comes at a price of accuracy. After a while only changes in the most significant parts of the number can be reflected. As seen in the following code snippet:

double large_num = Math.pow(10,200);
System.out.println("large_num == (large_num + 1000): " + (large_num == (large_num + 1000))); //true

At large integer values the steps between numbers are very very large since the double has no place to record the change if it doesn’t affect its most 16 most significant digits. As shown above 1000 plus a very large number is still that same very large number.

Infinity

Java’s double supports two kinds of infinity. Positive and negative inifity. The easiest to make those are by dividing by 0.

double pos_infinity = 5.0/0;
System.out.println("POSITIVE_INFINITY == pos_infinity: " + (Double.POSITIVE_INFINITY == pos_infinity));

double neg_infinity = -5.0/0;
System.out.println("NEGATIVE_INFINITY == neg_infinity: " + (Double.NEGATIVE_INFINITY == neg_infinity));

In maths infinity is a numerical concept representing the idea of an infinitly large number. It is used, for example in calculus, to describe an unbounded limit — some number that can grow without bound.

In this case things are pretty much the same as in maths, where POSITIVE_INFINITY and NEGATIVE_INFINITY are used to represent numbers that
are infinitely large. However they function more as a way to know something went wrong in your calculation. You are either trying to calculate something that is too large to store in a double or there is some bug in the code.

There are once again some interesting things to note when playing with positive and negative infinity.

double pos = Double.POSITIVE_INFINITY;

System.out.println("POSITIVE_INFINITY + 1000 = " + (pos + 1000));
System.out.println("POSITIVE_INFINITY + 10^1000 = " + (pos + Math.pow(10,1000)));
System.out.println("POSTIVE_INFINITY * 2 = " + (pos * 2));

Once the value is infinity it stays there even if you add or substract rediculously large numbers. However there is one interesting case, when you substract infinity from infinity:

double pos = Double.POSITIVE_INFINITY;
double neg = Double.NEGATIVE_INFINITY;

System.out.println("POSITIVE_INFINITY - POSITIVE_INFINITY = " + (pos - pos));
System.out.println("POSITIVE_INFINITY + NEGATIVE_INFINITY = " + (pos + neg));

Subtracting infinity from infinity yields NaN and as you would expect adding or subtracting NaN yields a NaN again.

System.out.println("POSTIVE_INFINITY + NaN" + (pos + Double.NaN));
System.out.println("POSTIVE_INFINITY - NaN" + (pos - Double.NaN));

In closing

Both Java’s float and double types follow the IEEE 754-1985 standard for representing floating point numbers. I am not going to go into great detail on the internals of double, but it suffice to say that double and float are not perfectly accurate when you use them to perform arithmetic. The Java primitive type documentation says:

This data type should never be used for precise values, such as currency. For that,
you will need to use the java.math.BigDecimal class instead.

If precision is you main concern then it is generally better to stick with good old java.math.BigDecimal. BigDecimal is immutable which makes it nice to work with, but the most important thing is precision. You have absolute control over number precision, without the rounding or overflow surprises you get with double and float. However, if performance is the main concern it is better to stick with float or double and live with the inaccuracies.

For more information on how Java handles NaN, infinity and rouding read the documentation here.

Понравилась статья? Поделить с друзьями:
  • Как найти свою страницу в яндекс почте
  • Как найти человека по фотке через телефон
  • Как найти пушку галеон
  • Как найти кнопку ввод на ноутбуке
  • Как составить заявление на протечку крыши многоквартирного дома