Why does wont my for loop add fractions up to 1.0 / 10,000,000.0?

I need to add a number of fractions. I looked at other loops forwhen adding fractions, but did not encounter the problem I am having. The denominator of the fractions increases by 1.0 each time, until it adds 1.0 / 1.0 + 1.0 / 2.0 + .... + 1.0 / 150,000,000.0. My code worked for me, adding fractions until I go a little over 10,000,000 into my for loop. As soon as I switch, they say that 15 million people just do not print anything, and the program continues to work. What mistake did I make? Why will he not print the answer if he is above a certain number?

Here is the code:

float sum = 0;
float numerator = 1;
float denominator = 1;

for(float i = 1; i <= 10000000; i++)
{
    sum = ((float)numerator/denominator) + sum;
    denominator++;
}
System.out.println("The sum is " + sum);
+4
source share
2

1 float . float - 23 . 16 ( 2 24), float 1. , Math.ulp ( ).

if (denominator % 1000 == 0)
    System.out.println("Denominator is " + denominator + ", ulp is " + Math.ulp(denominator));

, , ulp 1.0.

...
Denominator is 1.6775E7, ulp is 1.0
Denominator is 1.6776E7, ulp is 1.0
Denominator is 1.6777E7, ulp is 1.0

2 24 ulp 2.0, 1.0 IEEE , .

double (53 ). , , 2 53. . , BigDecimal s.

+7

, , :

. , - , , . - - 1 .

, , float . :

public class Sum {

public static void main(String[] args) {
    // TODO Auto-generated method stub


    float sum = 0;
    float numerator = 1;
    int denominator = 1; //changed to int

    for(int i = 1; i <= 10000000; i++)
    {
        sum = (numerator/(float)denominator) + sum; //this casts denominator to float
        denominator++; //this will now increment integer

    }
    System.out.println("The sum is " + sum);




} 
}

:

+1

Source: https://habr.com/ru/post/1625923/


All Articles