The previous chapter of Infinity Adding was discussing in regard to storing two integer numbers in string format and how to apply a mathematical addition equation on the two strings of digits by adding one digit at a time to produce an answer.

When we are discussing in regard to a mathematical calculation, one of the important components is how to deal with numbers that have a fractional part. In the computer world, numbers that carry a fractional part are often called float or floating point values. When calculating a floating point value, a majority of computer’s program will not calculate the precise value. Computer’s program will often round a floating point value to get a near precise calculation. Sometimes even on basic mathematical equations that only involved addition, the computer can’t generate a precise floating point calculation.

For example, when you are working within the R 3.1.2’s environment and apply this mathematical equation of 5134.324 + -4714.3289. R will give you the answer of 419.995099999999. Nonetheless, if we were to calculate the answer manually, we know that the correct answer is 419.9951. This type of method is the computer’s standard basic method for calculating values with a decimal placement. However, what happened if we truly need a precise decimal point value to be calculated without rounding the answer, and the numbers that involve in the equation have the possibility to have more than five hundred digits behind the decimal? This is chapter two of Infinity Adding, “Decimal, Precise Float Calculation”.

Note: The source code of chapter one and two of the Infinity Addition subject are prototypes. The prototypes purposes are to demonstrate the procedures for adding large numbers together. They are not meant for a production environment due to efficiency issue. Chapter three will have a production version of the source code.

This is a sample log of the result I got from executing the script that attaches to this article compare to R’s built-in float calculation. For each answer, the one of the left is R’s answer, and the one on the right is the answer provided by the script at the end of this article.

[1] "Question: 5134.324 + -4714.3289" [1] "R Answer: 419.995099999999 | infiA: 419.9951" [1] "" [1] "Question: 8683.8073 + -8641.3102" [1] "R Answer: 42.4971000000005 | infiA: 42.4971" [1] "" [1] "Question: 3544.855 + -3636.4063" [1] "R Answer: -91.5513000000001 | infiA: -91.5513" [1] "" [1] "Question: 4719.3792 + -4738.3379" [1] "R Answer: -18.9587000000001 | infiA: -18.9587" [1] "" [1] "Question: 3216.7646 + -3309.5013" [1] "R Answer: -92.7366999999999 | infiA: -92.7367"

### How To Add Two Floating Numbers Together In String Format

When storing numbers with a fractional part in string format, the first challenge we would have when we are applying a mathematical equation on the string is the digits behind the decimal. The string of number can be split into an array, where one index of the array holds the digits before the decimal and the other index holds the digits behind the decimal. Nevertheless, there is a high possibility that the amount of digit behind the decimal that each string has can vary. That can be solved by padding zeroes on the right of the shorter string to make both strings of number contain the exact same amount of digits behind the decimal.

Besides array, we can also split one string with the fractional part into two strings. After the split, one string can carry the digits before the decimal, and the other string can carry the digits behind the decimal. Thus, if we were going to add two strings of numbers that contain a fractional part together, we can have up to four strings. An example of this would be if we were to add A and B together where both A and B does contain a fractional part. Then we would split A into two. Where A1 can contain the digits before the decimal and A2 contains the digits behind the decimal. The same scenario would also apply to B1 and B2.

When it comes to calculating the digits behind the decimal, we can pad zeroes to the right of B2 if B2 is shorter than A2 to produce the equivalent amount of digits behind the decimal or vice-versa if A2 is shorter than B2. Another method to this would be, instead of padding zeroes, we can read the longer string first from the right. As long as the position we read is not less than or equal to the largest position of the shorter string, we would not read from the shorter string, instead, we would assign a value of zero in lieu of the shorter string’s digit. The addition formula for calculating the digits behind the decimal would be the same as calculating the digits before the decimal. We only have one additional procedure when it comes to adding values that are behind the decimal, and it is the final carry-over value from the equation have to be carried over to the equation of adding the two strings of digits that are before the decimal.

In this chapter, the majority of the information is in regard to the source code and explanations of the programming procedures for the source code.

Let first start with evaluating the input value of the string. First I use a conditional statement to test if the string is positive or negative in value by looking at the first character in the string. If the first character in the string is a negative sign, the variable isaNeg will be assigned with the value of one, of which can also be equal to a boolean value of true. For anything else, we assign a zero value to isaNeg. In R we can get the first character in a string using the substr() function. The substr() function takes an input that is a type string variable and two integer values. The two integer values represent the first and the last position to get a character or many characters from the inputted string variable. In R programming language the first position in a string is position one.

Note that you can also use a boolean declaration here with a true or false value. Nevertheless, I used a digit value here for isaNeg in the prototype to demonstrates another method for evaluating and storing a true or false value.

isaNeg <- ifelse(substr(a,1,1) == "-", 1 , 0)

After evaluating whether if the string can be a negative value or not, I removed any plus or minus sign using R’s gsub function with a regex pattern to search for and remove any positive and negative sign at the beginning of the string. We would also want to remove leading zeroes. This is because leading zeroes before the decimal do not offer any additional value to the number.

a <- gsub("^[+-]+", "" , a) a <- gsub("^0+", "" , a);

We would then need to initialize a third evaluation on the input. If the user input .123 without putting a zero in front of the decimal then we have to append a single zero to the front of the decimal. Therefore, we would evaluate whether if the first character of the string is a decimal. If it is a decimal, we add a zero to the string. If the first character is not a decimal, the string will be itself. We can just simply check the first position of the string to for whether if that position does contain a decimal or not using R’s regexpr function. The regexpr function can evaluate a regex pattern as a matching condition. I’m using a regex conditional statement here instead of the substr() function is because I just want to demonstrate an alternative method that can produce the same result for the same procedure.

a <- ifelse(regexpr("^[.]{1}\\d{0,}", a) > -1 , paste("0",a,sep="") , a);

After the above evaluation, I then evaluate if the string does contain a decimal by using regex. If the string does contain a decimal, I will use R’s gsub() function with a regex pattern that can evaluate and remove all the digits that are before the decimal, including the decimal from A string. The leftover digits are then assigned to a variable name adec. Variable adec is now holding the digits that are behind the decimal. Since I did the previous procedure through a variable assignment statement, the value of string A has not changed. On the third code line below, I removed all the digits that are behind the decimal and including the decimal in the value of variable A. Variable A is now holding all the digits that are before the decimal.

if (regexpr("\\d{0,}[.]{1}\\d{0,}", a) > -1){ adec <- gsub("^[0-9]{0,}[.]", "", a); a <- gsub("[.][0-9]{0,}$", "", a); }

When it comes to the strings that contain the digits behind the decimal, in the event where they do not contain a value, it would be very inefficiency to add the empty strings together. Also, the digits behind the decimal have to be added together first before the digits before the decimal. To be able to execute the equation efficiently, we would have to wrap our code block for adding the digits behind the decimal right before the code block for adding the digits before the decimal. On the first two lines of the below code, adeclen and bdeclen are the lengths of the strings that contain the digits behind the decimal. The if statement code block will only execute if either one of the lengths of the strings that contain the digits behind the decimal is higher than zero. In others word, either adec or bdec need to have a length for the code block to execute.

adeclen <- nchar(adec) bdeclen <- nchar(bdec) if (adeclen > 0 || bdeclen > 0){ # Equation code goes here }

While reading through the strings in a while loop or in a for loop, let assume the “i” variable is the index count and we will use it as the read position value to get a digit from our strings. We would only read the string that contains the digits behind the decimal if the current position value in the “i” variable is lower than the string’s maximum length. If the read position is within the string length, we would get a digit from that string at that position. Then we would convert the digit that we just obtained to an integer format. For anything else, we assign a value of zero in lieu of the string’s value.

x <- ifelse(i <= adeclen, strtoi(substr(adec,i,i)), 0)

When calculating the carry-over value for the next equation, we simply evaluate if the temporary answer’s value is higher than nine. If the temporary result value is higher than nine then we would assign one to the carry-over value. In a mathematical addition equation that only involves two sets of digits then the carry-over value can never be larger than the value of one. In the temporary result value, for anything else that is below the value of nine, we would assign a zero value to the carry-over value.

When assigning a value to the output, it is a constant that we will always assign the rightmost digit from the temporary answer to the left of the output string. We can base our evaluations on two conditions to get the rightmost digit from the temporary answer. If the result value is higher than nine, we take a value of ten and subtract to the temporary result value. For anything else, we simply keep the result value. This method can only be applied to a mathematical addition equation. Also, we can only apply this method when adding only two sets of digits together. This is because the carry-over value can never be larger than a value of one.

temp <- x + y + carryOver carryOver <- ifelse(temp > 9, 1, 0) temp <- ifelse(temp > 9, temp - 10, temp) output <- paste(toString(temp), output, sep="")

After adding the entire two strings of digits behind the decimal together and the output string contained the full result value for the equation. We would then need to append a decimal point to the front of the output string before going into our next calculation. We then check for any zeroes to the right of the output string and remove all ending zeroes. As opposed to a whole number, trailing zeroes to the right side of the digits that are behind a decimal point do not provide any additional value. After removing all the zeroes, if the last character is only the decimal then we would also remove the decimal. The previous two procedures are done through R’s gsub() function on line two and three.

output <- paste(".", output, sep=""); output <- gsub("[0]{1,}$", "", output); output <- gsub("[.]$", "", output);

The above explanations are important code lines for adding a positive number to a positive number. Let discuss some important code lines for adding a positive number to a negative number. Or a negative number to a positive number. The principles for adding a positive value to a negative value can be described as subtracting the two values. The result value from this type of equation will carry the same negative or positive base as the larger value.

The example below is for the event of when the first string of input being the higher value string. In the first code line, we are subtracting the first string’s digit to the second string’s digit then to any carry-over value. For the second code line, we are assigning a carry-over value bases on a condition. If the result value is less than zero then we assign a value of one to the carry-over value. Otherwise, a value of zero is assigned to the carry-over value. This is easy to achieve when we are only dealing with two sets of digits. If we were dealing with more than two sets of digits then we would have to implement another method.

On the third code line, if the result value is less than zero, or in others word, a negative value. Then we would take a value of ten and add to the result value. Otherwise, we would not alter the result value. We then place the result value to the left of the output string, the code statement for this is on the fourth code line.

temp <- x - y - carryOver; carryOver = ifelse(temp < 0, 1, 0) temp <- ifelse(temp < 0, 10 + temp, temp) output <- paste(toString(temp), output, sep="")

The above is if the first input string is higher in value. When it’s come to the second input string that is higher in value, the equation’s procedures do not change, nevertheless, there are differences between the two equation. When comparing the first line of code to the above equation’s procedure, we are still subtracting the first string’s digit to the second string’s digit. Nonetheless, instead of subtracting to the carry-over value, we are now adding to the carry-over value. The main change in how we are assigning the carry-over value is the temporary result value has to be larger than zero for us to assign a value of one to the carry-over value.

On the third code line below, the ending is very important. The temporary result value that does not need to be modified is now negative in value. If we are going to convert a negative integer value to a string type format and then placing the value to the output string, we would have a minus sign between every digit. Thus, we can either subtract the temporary result value to itself twice to reach its positive value, convert the temporary result value to a string type and grab the rightmost digit, or simply, multiply the temporary result value to a negative value of one.

temp <- x - y + carryOver; carryOver <- ifelse(temp > 0, 1 , 0) temp <- ifelse(temp > 0, 10 - temp, temp - temp - temp) output <-paste(toString(temp), output, sep="")

The code is below is the full function of this tutorial.

**Advertisement**

# "Copyright Notice", please do not remove. # Written by Kevin Ng # The full tutorial on this subject can be found @ http://kevinhng86.iblog.website or http://programming.world.edu. # Release date to http://programming.world.edu will lag one week after release on http://kevinhng86.iblog.website # This source code file is a part of Kevin Ng's Z library. # This source code is licenses under CCDL-1.0 A copy of CDDL1.0 can be found at https://opensource.org/licenses/CDDL-1.0 # End "Copyright Notice" # Notice: This is version 1 of infiA from Kevin Ng's LibZ library. # This is not a production version and is a prototype. # This version has been tested, but would be too slow in a production environment. # This version of infiA support mathematical addition without the decimal. infiA <- function (a, b){ isaNeg <- ifelse(substr(a,1,1) == "-", 1 , 0) isbNeg <- ifelse(substr(b,1,1) == "-", 1 , 0) a <- gsub("^[+-]+", "" , a) b <- gsub("^[+-]+", "" , b) a <- gsub("^0+", "" , a) b <- gsub("^0+", "" , b) a <- ifelse(regexpr("^[.]{1}\\d{0,}", a) > -1 , paste("0",a,sep="") , a) b <- ifelse(regexpr("^[.]{1}\\d{0,}", b) > -1 , paste("0",b,sep="") , b) adec <- "" bdec <- "" if (regexpr("\\d{0,}[.]{1}\\d{0,}", a) > -1){ adec <- gsub("^[0-9]{0,}[.]", "", a) a = gsub("[.][0-9]{0,}$", "", a) } if (regexpr("\\d{0,}[.]{1}\\d{0,}", b) > -1){ bdec <- gsub("^[0-9]{0,}[.]", "", b) b <- gsub("[.][0-9]{0,}$", "", b) } aidx <- nchar(a) bidx <- nchar(b) adeclen = nchar(adec) bdeclen = nchar(bdec) x <- 0 y <- 0 carryOver <- 0 temp <- 0 output <- "" if (isaNeg == isbNeg){ if (adeclen > 0 || bdeclen > 0){ i <- ifelse( adeclen > bdeclen, adeclen, bdeclen) while (i > 0){ x <- ifelse(i <= adeclen, strtoi(substr(adec,i,i)), 0) y <- ifelse(i <= bdeclen, strtoi(substr(bdec,i,i)), 0) temp <- x + y + carryOver carryOver <- ifelse(temp > 9, 1, 0) temp <- ifelse(temp > 9, temp - 10, temp) output <- paste(toString(temp), output, sep="") i = i - 1 } output <- paste(".", output, sep="") output <- gsub("[0]{1,}$", "", output) output <- gsub("[.]$", "", output) } while (aidx > 0 || bidx > 0){ x <- ifelse(aidx > 0, strtoi(substr(a,aidx,aidx)), 0) y <- ifelse(bidx > 0, strtoi(substr(b,bidx,bidx)), 0) temp <- x + y + carryOver carryOver <- ifelse(temp > 9, 1, 0) temp <- ifelse(temp > 9, temp - 10, temp) output <- paste(toString(temp), output, sep="") output <- ifelse(aidx < 2 && bidx < 2, paste(toString(carryOver), output, sep=""), output) aidx <- aidx - 1 bidx <- bidx - 1 } output <- gsub("^0+", "", output ) output <- ifelse(nchar(output) < 1 || regexpr("^[.]{1}\\d{0,}", output) > 0 , paste("0",output,sep=""), output) return(ifelse(isaNeg == 1 && isbNeg == 1, paste("-", output, sep="") ,output)) } else if (isaNeg != isbNeg){ larger <- ifelse(nchar(a) > nchar(b), "a" , ifelse(nchar(b) > nchar(a), "b" , "1")) if (larger == "1"){ larger <- "" for (i in 1:nchar(a)){ larger <- ifelse(strtoi(substr(a,i,i)) > strtoi(substr(b,i,i)), "a", larger) larger <- ifelse(strtoi(substr(b,i,i)) > strtoi(substr(a,i,i)), "b", larger) if (nchar(larger) > 0){ break } larger <- ifelse((i == nchar(a) && nchar(larger) < 1), "0" , larger) } if ((adeclen > 0 || bdeclen > 0 ) && larger == "0"){ max <- ifelse(adeclen > bdeclen, adeclen , bdeclen) for (i in 0:max){ x <- ifelse(i <= adeclen, strtoi(substr(adec,i,i)), 0) y <- ifelse(i <= bdeclen, strtoi(substr(bdec,i,i)), 0) larger <- ifelse(x > y, "a", ifelse(y > x, "b" , "0")) if (larger == "a" || larger == "b"){ break } } } } if (larger == "0"){ return(larger) } else if (larger == "a"){ if (adeclen > 0 || bdeclen > 0){ i <- ifelse(adeclen > bdeclen, adeclen, bdeclen) while (i > 0){ x <- ifelse(i <= adeclen, strtoi(substr(adec,i,i)), 0) y <- ifelse(i <= bdeclen, strtoi(substr(bdec,i,i)), 0) temp <- x - y - carryOver; carryOver = ifelse(temp < 0, 1, 0) temp <- ifelse(temp < 0, 10 + temp, temp) output <- paste(toString(temp), output, sep="") i <- i - 1 } output <- paste(".", output, sep="") output <- gsub("[0]{1,}$", "", output) output <- gsub("[.]$", "", output) } while (aidx > 0) { x <- strtoi(substr(a,aidx,aidx)) y <- ifelse(bidx > 0, strtoi(substr(b,bidx,bidx)), 0) temp <- x - y - carryOver carryOver <- ifelse(temp < 0, 1 , 0) temp <- ifelse(temp < 0, 10 + temp, temp) output <- paste(toString(temp), output, sep="") aidx <- aidx - 1 bidx <- bidx - 1 } output <- gsub("^0+", "", output ) output <- ifelse(regexpr("^[.]{1}\\d{0,}", output) > 0, paste("0",output,sep=""), output) return(ifelse(isaNeg == 1, paste("-", output, sep=""), output)) } else if (larger == "b"){ if (adeclen > 0 || bdeclen > 0){ i <- ifelse(adeclen > bdeclen, adeclen , bdeclen) while (i > 0){ x <- ifelse(i <= adeclen, strtoi(substr(adec,i,i)), 0) y <- ifelse(i <= bdeclen, strtoi(substr(bdec,i,i)), 0) temp <- x - y + carryOver carryOver <- ifelse(temp > 0, 1 , 0) temp <- ifelse(temp > 0, 10 - temp, temp - temp - temp) output <-paste(toString(temp), output, sep="") i <- i - 1 } output <- paste(".", output, sep="") output <- gsub("[0]{1,}$", "", output) output <- gsub("[.]$", "", output) temp <- 0 } while (bidx > 0){ x <- ifelse(aidx > 0, strtoi(substr(a,aidx,aidx)), 0) y <- strtoi(substr(b,bidx,bidx)) temp <- x - y + carryOver carryOver <- ifelse(temp > 0, 1 , 0) temp <- ifelse(temp > 0, 10 - temp, temp - temp - temp) output <- paste(toString(temp), output, sep="") aidx <- aidx - 1 bidx <- bidx - 1 } output <- gsub("^0+", "", output) output <- ifelse( regexpr("^[.]{1}\\d{0,}", output) > 0, paste("0",output,sep=""), output) return(ifelse(isaNeg == 0, paste("-", output, sep="") , output)) } } } c <- "999999999999999999999999999999999999.999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999" d <- "999999999999999999999999999999999999.999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999" e <- infiA(c, d) print(e)

This post was written by Kevin and was first post @ http://kevinhng86.iblog.website.

Original Post Name: "Working With Number – Infinity Adding – Decimal, Precise Float Calculation – R".

Original Post Link: http://kevinhng86.iblog.website/2017/02/08/working-with-number-infinity-adding-decimal-precise-float-calculation-r/.

**Advertisement**