# Finding frequency and probability of characters in a string

• October 30th, 2010, 09:23 AM
Aberforth
Finding frequency and probability of characters in a string
***Problem****In this program if the frequency is large (say, 9) the frequency shows it as 9.000000000006.
Code java:

```import java.io.*;   public class Freq {   public static void main(String[] args) { System.out.println("Type string : "); String str = ""; InputStreamReader input = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(input);     try {   str = reader.readLine();   } catch (Exception e) { } System.out.println("String is : " + str);//part 2 string input   /*finding frequency of characters*/ double len = str.length(); double count = 0; double prob = 0; double ref = 1000; double freq = 0; double prqueue[] = new double[96]; char charArr[] = new char[96]; double temp = 0; char flag;   for (int i = 0; i < 96; i++) { char currChar = (char) (32 + i); for (int k = 0; k < len; k++) { char currStrChar = str.charAt(k); if (currChar == currStrChar) { count = count + (1 / ref);//this is used if the file is too large   }   } freq = count * ref; prob = freq / len; if (freq != 0) { System.out.println("occurence of " + currChar + ": " + freq + " and probability is : " + prob); } prqueue[i] = prob; charArr[i] = currChar; count = 0;     }     System.out.println(); System.out.println(); System.out.println("PRIORITY QUEUE :"); /*priority queue*/ for (int x = 0; x < 95; x++) { for (int y = 0; y < 95 - x - 1; y++) { if (prqueue[y] > prqueue[y + 1]) { temp = prqueue[y]; flag = charArr[y]; prqueue[y] = prqueue[y + 1]; charArr[y] = charArr[y + 1]; prqueue[y + 1] = temp; charArr[y + 1] = flag; } } }   for (int x = 0; x < 95; x++) { if (prqueue[x] != 0) { System.out.println(charArr[x] + " has value in priority queue " + prqueue[x] + ", "); } } } }```
• October 30th, 2010, 10:49 AM
copeg
Re: Finding frequency and probability of characters in a string
Quote:

Originally Posted by Aberforth
***Problem****In this program if the frequency is large (say, 9) the frequency shows it as 9.000000000006.

Why is that a problem? What do you expect/want to see?
• October 30th, 2010, 10:55 PM
Aberforth
Re: Finding frequency and probability of characters in a string
actually the frequency should be an integer i.e,9.0000000000 and not 9.0000000006.
• October 30th, 2010, 11:54 PM
Darryl.Burke
Re: Finding frequency and probability of characters in a string
Quote:

actually the frequency should be an integer
Then why are you using a double?

db
• October 31st, 2010, 02:02 AM
Aberforth
Re: Finding frequency and probability of characters in a string
i am using double because probability will have a decimal part.
but when i am going to find the frequency , the decimal part should be entirely zero.
for example, the string be: aaaabbbbbbbbbbbccc
the frequency of 'b' must be 11.
but when i run the program, the frequency is shown as 11.0000000000004.
i am confused about the .00000000004 part.