How to write an EBNF grammar for Java float literals? - Computer Science Stack Exchange most recent 30 from cs.stackexchange.com 2019-09-18T14:08:39Z https://cs.stackexchange.com/feeds/question/53284 https://creativecommons.org/licenses/by-sa/4.0/rdf https://cs.stackexchange.com/q/53284 0 How to write an EBNF grammar for Java float literals? Mkey https://cs.stackexchange.com/users/46564 2016-02-18T14:26:42Z 2016-02-18T20:53:31Z <p>I've got this question on my study guide: "Write an EBNF grammar description for Java float literals and one for Java double literals."</p> <p>I've browsed the Oracle site and found the grammar for java float literals, but I'm not entirely sure how to convert that to EBNF grammar. I understand EBNF notation but for some reason I'm stuck on this.</p> <p>I was hoping/wondering someone would be able to get me started? It would be highly appreciated.</p> https://cs.stackexchange.com/questions/53284/-/53285#53285 -1 Answer by Konstantin Yovkov for How to write an EBNF grammar for Java float literals? Konstantin Yovkov https://cs.stackexchange.com/users/42832 2016-02-18T14:59:15Z 2016-02-18T20:53:31Z <p>You could try answer the question <em>"How do I define <code>double</code> and <code>float</code> literals?"</em></p> <p><code>double</code>s are usually defined as:</p> <pre><code>double a = 12d; //or double b = 12.1; //or double c = 12.1d; //or double d = 12; </code></pre> <p>while <code>float</code>s could be defined as:</p> <pre><code>float m = 10; //or float n = 10.4f; //but this is invalid: float p = 10.4; </code></pre> <p>Note that by default a literal like <code>10.123</code> is considered to be <code>double</code>, so if you really want to assign it to a <code>float</code> variable, you need to append a <code>f</code> character in the end. However, <code>f</code> is optional when the literal is <code>10</code>.</p> <p>Let's also list the properties of both types:</p> <p><code>float</code>: 32 bits (4 bytes) where 23 bits are used for the mantissa (up to 9 decimal digits). 8 bits are used for the exponent, so a float can <em>move</em> the decimal point to the right or to the left using those 8 bits. There is 1 bit used as the sign bit. The max <code>long</code> value that double can hold is \$10_18\$</p> <p><code>double</code>: 64 bits (8 bytes) where 52 bits are used for the mantissa (up to 19 decimal digits). 11 bits are used for the exponent and 1 bit is the sign bit.</p> <p>So, <code>double</code> and <code>float</code> could be defined like:</p> <pre><code>digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"; double = 19 * digit, [ [, | .] 18 * digit]["d" | "D"]; float = 19 * digit, [ [, | .] 18 * digit, "f" | "F"]; </code></pre>