Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent scientific notation in C

How do I represent extremely large or small numbers in C with a certain amount of significant figures. For example, if I want to do calculations on 1.54334E-34, how could I do this. Also, is this applicable to OpenCL code?

like image 978
user1876508 Avatar asked Jun 03 '13 21:06

user1876508


People also ask

How do you write exponential notation in C?

Because it can be hard to type or display exponents in C++, we use the letter 'e' (or sometimes 'E') to represent the “times 10 to the power of” part of the equation. For example, 1.2 x 10⁴ would be written as 1.2e4 , and 5.9736 x 10²⁴ would be written as 5.9736e24 .

What is %g in C?

%g. It is used to print the decimal floating-point values, and it uses the fixed precision, i.e., the value after the decimal in input would be exactly the same as the value in the output.

How do you type a scientific notation?

For scientific notation, you can type either a caret (^) or the letter e followed by a number to indicate an exponent. You can use both positive and negative exponents. For example, to indicate 0.012 , you can enter either of the following expressions: 1.2*10^-2.


2 Answers

float var = 1.54334E-34;
double var2 = 1.54334E-34;

printf("\n normal:%f\n sci:%e \n or \n sci:%E   \n",var,var,var);
printf("\n normal:%f\n sci:%e \n or \n sci:%E   \n",var2,var2* 1.0E3 ,var2 * 1.0e3);
like image 58
mf_ Avatar answered Nov 08 '22 12:11

mf_


I don't know any OpenCL but 32-bit C floats will hold values in the range of +/- 3.4e +/- 38 (~7 digits), and doubles much more. If you want arbitrary precision arithmetic/math you may want to look into GMP or MPFR.

like image 36
Kninnug Avatar answered Nov 08 '22 11:11

Kninnug