I need to specify that I need two numbers be the same upon 3rd decimal place: 1.2345 and 1.2348 is correct. But 1.2345 and 1.2388 is not correct. And I need let user specify how many places should program check.
I was thinking about something like that:
do {
x = f(i++);// will count some number with i iterations
x_next = f(i++);// will count some number with i+1 iterations
} while (fabs(x - x_next) > accuracy);// there should be some difference, cause more iterations = accurate number, but different numbers = different iterations needed
But I don't know how should I convert number 3 to 0.001.
Can you suggest me something please?
Divide 1.0 by 10 3 times to get 0.001.
To convert 3 to .001 use the pow() function. .001 = pow(10, -3) (It returns base to the power of exponent, in this case 10^-3.) You would need to include the math.h library to use pow().
A word of caution. abs(x-y)<.001 does not guarantee that they agree on 3 decimal places. For example, 1.00000 and .99999 don't agree on any decimal places but abs(1.00000-.99999)=.00001 < .001.
If you need to check if two numbers are the same upon 3rd decimal place, you can simply multiply both values with 1000 and compare them as integers.
You get the picture, you have to mutiply with 10^decimal_place.
EDIT:
If rounding is required, then simply add 5/10^(decimal_place+1) before multiplying.
Well, there is two ways to approach this:
If you want to see if the difference of two numbers is less than 10 to the power of minus your number (in your example 0.001), you can use the solutions provided. However, it says 1.3458 is equal to 1.3462, which doesn't seems what you wanted.
You can convert the numbers to integers before. In your example (3 decimal places), you can multiply your number by 1000 (10 to the power of 3), and get it's integer part (with an (int) cast), as in:
int multiplier = pow(10,decimalPlaces);
int number1 = (int) numberOriginal1*multiplier;
int number2 = (int) numberOriginal2*multiplier;
if(number1 == number2)
printf("Success\n");
else printf("Fail\n");
Hope that helps.
If you just want to give it as an output simply use printf("%.3f",number)
or if you want to it other way, just go through this question,
Rounding Number to 2 Decimal Places in C
Related
For a class project I need to split some audio clips in smaller sections, for which we are provided a min length and a max length, to figure out whether this is possible, I do the following:
a = length/max
b = length/min
mathematically I figured that [a,b] contains at least one integer if ⌊b⌋ >= ⌈a⌉, but I can't use math.h for floor() and ceil(). Since a and b are always positive I can use type casting for floor(), but I am at a loss at how to do ceil(). I thought about using ((int)x)+1 but that would round integers up which would break the formula.
I would like either a way to do ceil() which would solve my problem, or another way to check whether an interval contains at least one integer.
You don't need the math.h to perform floor. Please look at the following code:
int length=5,min=2,max=3; // only an example of inputs.
int a = length/max;
int b = length/min;
if(a!=b){
//there is at least one integer in the interval.
}else{
if(length % min==0 || length % max==0 ){
//there is at least one integer in the interval.
}else{
//there is no integer in the interval.
}
}
The result for the above example will be that there is an integer in the interval.
You can also perform ceil without using math.h as following:
int a;
if(length % max == 0){
a = length / max;
}else{
a = (length / max) + 1;
}
If I understood you question right, I guess, you can do ceil(a) in this case, and then check if the result is less then b. Thus, for example, for interval [1.3, 3.5], ceil(1.3) will return 2, which fits into this interval.
UPD
Also you could do (b - a). If it's > 1, there's for sure at least one integer between them.
There is a general trick in programming that will come in hand if you ever find yourself programming Apple Basic, or any other language where floating point math is supported.
You can "round" a number by addition, then truncation, as follows:
x = some floating value
rounded_x = int(x + roundoff_amount)
Where roundoff_amount is the difference between the lowest fraction to round up, and 1.
So, to round at .5, your round_off would be 1 - .5 = .5, and you would do int(x + .5). If x is .5 or .51 then the result becomes 1.0 or 1.01 and int() takes that to 1. Obviously, if x is higher, then you still get rounded to 1, until x becomes 1.5 when rounding takes it to 2. To round upwards starting at .6, your roundoff amount would be 1 - .6 = .4, and you would do int(x + .4), etc.
You can do a similar thing to get ceil behavior. Set your roundoff_amount to be 0.99999... and do the round. You can choose your value to provide a "nearby" window, since floats have some inaccuracy inherent that might prevent getting a perfectly integer value after adding fractions.
Is there any way to ensure that a floating-point variable entered by the user, having 2 decimal places after the decimal point, retains its exact value, rather than losing precision?
This is the example case:
I want to round a float with 50 numbers after radix point, like this
Before rounding = 0.70999997854232788085937500000000000000000000000000
to this:
After rounding = 0.71000000000000000000000000000000000000000000000000
I became confused when I wanted to compare a float number in a condition like this:
== Program Start==
Input : 0.71
/* program logic */
if (input == 0.71) {
printf("True !");
} else {
printf("False !");
}
Output : False !
==Program End==
The output was False ! and will always be False ! because the true value of user's input is 0.70999997854232788085937500000000000000000000000000, and not 0.71000000000000000000000000000000000000000000000000
Is there any way to round a float value like that? I read about the potential for inaccuracies with floating point here:
Why Are Floating Point Numbers Inaccurate?
and followed it to these links: Is there a function to round a float in C or do I need to write my own?
and Rounding Number to 2 Decimal Places in C
However, these don't answer my question. If I use ceilf(input * 100) / 100 function, it will make the input 0.71 into 0.71000 when printf()d using %.5f format - which seems to work. But when I print with %.50f, the real input value appears as 0.709999978542327880859375. So, I can't compare to that value in my condition.
So, if floating point can never be accurate, what is the trick for the program logic above to get a true return value at that condition?
All of the user's input comes in as text. The easiest -- and, possibly, safest -- way to check it is to compare it as a string before even converting to number:
if (strcmp("0.71", input) == 0) {
printf("True !");
} else {
printf("False !");
}
Of course, this may not be acceptable to you, if you wish to check for something other than equality :)
The other point is that you are interested in fixed, rather than floating numbers here -- but are confusing them with actual integers. If hundredths is what you'd like to work with, then work with the integer numbers of hundredths... For example, consider money -- instead of using float (or double) to store the amounts of dollars (like $7.61), use int (or, god bless you, long) to store cents (like ¢761).
Similarly, for another example, if you are counting time and need precision of one thousandth of a second, then use integer numbers of milliseconds, instead of floating-point number of seconds.
This will sidestep your entire problem altogether and may also make your programs faster...
I'm sure this question has been answered before, however:
float rounded_down = floorf(input * 100) / 100; /* Result: 0.70 */
float nearest = roundf(input * 100) / 100; /* Result: 0.71 */
float rounded_up = ceilf(input * 100) / 100; /* Result: 0.71 */
The library this functions belongs I think is math.h.
You can test equality with a range as you've experienced.
Just rewrite your equality test with:
if(input <= .71 + EPSILON && input >= .71 - EPSILON) {
}
Here you can create your own EPSILON based on your tolerance, or you can perhaps use FLT_EPSILON from #include<cfloat> for C++ or #include <float.h> in C.
Recall that floats do not have 50 digits of decimal precision. So trying to round at the 50th decimal place isn't going to work out so well. Floats have about 6 (sometimes more) digits of precision.
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 8 years ago.
So I've been attempting to solve the 3SUM problem and the following is my algorithm
def findThree(seq, goal):
for x in range(len(seq)-1):
left = x+1
right = len(seq)-1
while (left < right):
tmp = seq[left] + seq[right] + seq[x]
if tmp > goal:
right -= 1
elif tmp < goal:
left += 1
else:
return [seq[left],seq[right],seq[x]]
As you can see it's a really generic algorithm that solves it in O(n2).
The problem I've been experiencing is that this algorithm doesn't seem to like working with floating point numbers.
To test that my theory is right, I gave it the following two array
FloatingArr = [89.95, 120.0, 140.0, 179.95, 199.95, 259.95, 259.95, 259.95, 320.0, 320.0]
IntArr = [89, 120, 140, 179, 199, 259, 259, 259, 320, 320]
findThree(FloatingArr, 779.85) // I want it to return [259.95, 259.95, 259,95]
>> None // Fail
findThree(FloatingArr, 777) // I want it to return [259,259,259]
>> [259, 259, 259] // Success
The algorithm does work, but it doesn't seem to work well with floating point numbers. What can I do to fix this?
For additional information, my first array is originally a list of string of prices, but in order to do math with them, I had to strip the "$" sign off. My approach in doing so is this
for x in range(len(prices)):
prices[x] = float(prices[x][1:]) // return all the prices without the "$" sign. Casting them to float.
If there is a much better way, please let me know. I feel as if this problem is not really about findThree() but rather how I modified the original prices array.
Edit: Seeing that it is indeed a floating point problem, I guess my next question would be what is the best way to convert a string to int after I strip off the "$" ?
It doesn't work because numbers like 89.95 typically cannot be stored exactly (because the base-two representation of 0.95 is a repeating decimal).
In general, with dealing with floating-point numbers, instead of comparing for exact equality via ==, you want to check if the numbers are "close enough" to be considered equal; typically done with abs(a - b) < SOME_THRESHOLD. The exact value of SOME_THRESHOLD depends on how accurate you want to be, and typically requires trial and error to get a good value.
In your specific case, because you're working with dollars and cents, you can simply convert to cents by multiplying by 100 and rounding to an integer (via round, because int will round ie 7.999999 to 7). Then, your set of numbers will just be integers, solving the rounding problem.
You can convert your prices from string to integers instead of converting them to floats. Let's assume that all prices have at most k digits after the decimal point(in initial string representation). Then 10^k * price is always a whole number. So you completely can get rid of floating-point computations.
Example: if there are at most two digits after the decimal point, $2.10 becomes 210 and $2.2 becomes 220. There is no need to use float even in intermediate computations because you can shift decimal point by two positions to the right(appending zeros if necessary) and then convert a string directly to an integer.
Here is an example of convert function:
def convert(price, max_digits):
""" price - a string representation of the price
max_digits - maximum number of digits after a decimal point
among all prices
"""
parts = price[1:].split('.')
if len(parts) == 2 and len(parts[1]) > 0:
return int(parts[0]) * 10 ** max_digits + \
int(parts[1]) * 10 ** (max_digits - len(parts[1]))
else:
return int(parts[0]) * 10 ** max_digits
I need to write a program in C that does the following:
Write a program so that when the user enters a floating point number, it rounds off the number to 3 decimal places. When displaying the result, display 5 decimal places, and this means the 4th and 5th decimal place number will both be 0.
How do I round it to 3 decimal places and then display two zeroes? I am not allowed to use any sort of math library functions.
printf("%.5f\n",(int)(number*1000+0.5)/1000.0);
Well, "no math" method :D
printf("%.3f00\n", n);
(Usually subject to Round-to-Nearest-Even; see R..'s comment.)
There are two steps to your task:
1) Round the number to three (3) decimal places.
double n = 0.123456;
n = ((int) (n * 1000.0)) / 1000.0; // => 0.123
2) Display the number to five (5) decimal places.
printf("%.5f\n", n); // => 0.12300
I am writing a program in C.
Is there any way of determining the number of decimal places
in a float number (i.e. 0.123 = 3, 0.123456 = 6 etc.)?
Other than converting the number to a string and using string
functions to pull the characters after the decimal place?
I have a function named computeFare()
float computeFare()
{
totalFare = (3.40 + basicFare) * (1 + surchargePercent);
return totalFare; // **in this case totalFare = 34.567**
}
printf("Total fare is $%.2f\n",
computeFare());
Result : Total fare is $34.56
I did this and it returned 34.56...
I want it to be $34.57
Thanks,
Lawrence.
Not really, the number of decimal places is a function of the internal representation of the number. What you see when you display the number is, is the number as a string for printing.
So if you are interested in the displayed value, you can control the number of decimal places with formatting directives in the first place e.g., %5.2f, or use the string function approach as you mention in your post after the fact once you have the number as a string.
Also, as an aside, would you count trailing zeros?
Perhaps it would be helpful to state your goal for wanting to do this? There might be other ways to accomplish what you are looking to do.
Update:
Based on your update, the problem is really not counting decimal places, rather you are running into represenation issue/rounding errors (not that uncommon). The problem is that some fractional values can't be exactly represented in base 2. Here's an exhaustive explanation: What Every Computer Scientist Should Know About Floating-Point Arithmetic.
Take a look at this SO question: Understanding floating point representation errors; what's wrong with my thinking?
You can try this approach to round the value:
float rounded_val = floorf(value * 100.0 + 0.5) / 100.0;
Wikipeadia has a whole article on rounding.
The numbers will (in general) be stored in base 2, so fractional numbers are unlikely to correspond precisely to concise decimal strings. In order to get neat decimals, you're probably going to have to round first.
With printf you can specify the amount of decimal places.
%.0f equals no decimal places
%.4f equals float showing four decimal places
A. I wouldn't think so. even if you could get the mantisa (the exponent value) it would be in base 2.
B. Moreover, floating numbers are not accurate so most likely that if you don't have a perfect round number that you have infinite number of decimal places. you wouldn't see them when you print the number cause there are getting cut.
After your latest edit, it sounds like you just want to round, not that you really care about the number of decimal places in a number.
If this is the case you can use code like this:
#include <math.h>
float computeFare()
{
float totalFare;
totalFare = (3.40 + basicFare) * (1 + surchargePercent);
totalFare = floorf(totalFare * 100 + 0.5) / 100; //round the answer
return totalFare; // **in this case totalFare = 34.567**
}
printf("Total fare is $%.2f\n", computeFare());