5 kyu
Going to zero or to infinity?
869 of 6,163g964
Loading description...
Mathematics
Algorithms
View
This comment has been reported as {{ abuseKindText }}.
Show
This comment has been hidden. You can view it now .
This comment can not be viewed.
- |
- Reply
- Edit
- View Solution
- Expand 1 Reply Expand {{ comments?.length }} replies
- Collapse
- Spoiler
- Remove
- Remove comment & replies
- Report
{{ fetchSolutionsError }}
-
-
Your rendered github-flavored markdown will appear here.
-
Label this discussion...
-
No Label
Keep the comment unlabeled if none of the below applies.
-
Issue
Use the issue label when reporting problems with the kata.
Be sure to explain the problem clearly and include the steps to reproduce. -
Suggestion
Use the suggestion label if you have feedback on how this kata can be improved.
-
Question
Use the question label if you have questions and/or need help solving the kata.
Don't forget to mention the language you're using, and mark as having spoiler if you include your solution.
-
No Label
- Cancel
Commenting is not allowed on this discussion
You cannot view this solution
There is no solution to show
Please sign in or sign up to leave a comment.
Haskell fork
This code dont handle well for Java langauge
the reference solution was rounding, and the assertions' delta was much too low (
1e-10
instead of1e-6
). fixed.Unfortunately the code I created using go experienced a time out
This comment has been hidden.
fixed by using
for the assertion
Kata is nearly unplayable in Clojure due to strict equality checking. Please fix.
already raised here
Lua translation!
wrong test missing import
This comment has been hidden.
fixed
This is marked as resolved, but still seems to be a problem for the sample test cases.
Julia fork switching to approximate equality with tolerance of 1e-6
approved
For rounding issues with R, you don't want to round, you want to throw away everything after the 6th decimal.
how is truncating better than rounding ?
The only correct thing to do is to use approximate equality, about which i have already raised an issue just below.
It's not better, but it's what I had to do to get my R solution to work. Sorry maybe not clear, this is a tip for solutions rather than improving the kata.
R version fixed ;-)
Some languages still use rounding + strict equality instead of approximate equality with no rounding:
better assertion messages for C
Approved.
The Attempt throw me this error: "expected NaN to equal 1.005025" but all good with the tests, and the console.logs, the problem is when i try to return the result
Not a kata issue.
I have that problem too
This comment has been hidden.
C#: method name should be
PascalCase
(Please refer to implementation of backward compatibility here )Fixed__Tests Log Correct, but C++:
UndefinedBehaviorSanitizer:DEADLYSIGNAL ==1==ERROR: UndefinedBehaviorSanitizer: FPE on unknown address 0x000000428831 (pc 0x000000428831 bp 0x7ffefa15a0d0 sp 0x7ffefa159c50 T1) ==1==WARNING: invalid path to external symbolizer! ==1==WARNING: Failed to use and restart external symbolizer! #0 0x428830 (/workspace/test+0x428830) #1 0x42702e (/workspace/test+0x42702e) #2 0x426a5d (/workspace/test+0x426a5d) #3 0x42674b (/workspace/test+0x42674b) #4 0x42a925 (/workspace/test+0x42a925) #5 0x425f3d (/workspace/test+0x425f3d) #6 0x7fd145f8bc86 (/lib/x86_64-linux-gnu/libc.so.6+0x21c86) #7 0x404619 (/workspace/test+0x404619)
UndefinedBehaviorSanitizer can not provide additional info. ==1==ABORTING
Your solution has a bug, it crashes for n = 20.
Thank you so much for answer! Thanks!
Hi. There is an issue with the TypeScript/JavaScript version of this question. The maximum value in both of these languages for integers is
Number.MAX_VALUE === 1.7976931348623157e+308 Any factorial greater than 170 will give an integer of above 7.257415615307994e+306 which javascript will interpret to infinity causing the 1/n! to go to NaN
just I know some people are having this problem and maybe theres a fix but I figured I would raise the issue regardless. Python has an upperbound on integers based off device limit so if anyone attempting JS/TS has the same issue but want the challenge of solving the problem still they can try python ✌🏻
Not a kata issue. Your code is unskilful and because of that you have a problem. Notice how many people passed the kata in TS or JS (see top of the page).
Instead of giving a hint, you're being toxic.Nice man👍
Please could someone point me in the right direction towards simplifying the expression as I'm lost. I'm not asking for the answer just a little more information.
This comment has been hidden.
going <- function (n) { # your code c <- c() for (i in 1:n){ a <- factorial(i) c <- sum(c,a) } d <- (1/factorial(n))*c return(d) }
the code works in vscode but fails on the website, why?
This comment has been hidden.
The description mentions: "To avoid discussions about rounding, return the result truncated to 6 decimal places, ...". You say: "even though my rounding method does what the description asks: return(sum*1e6).rounded(.down)*1e-6.".
I tried your solution with an 'usual method' "floor(sum * 1e6) / 1e6" several times and had no problem. Note: "return(sum*1e6).rounded(.down) / 1e6." works very well too. Besides that I notice that ""1.1466509999999999" has clearly more than 6 decimal places; Swift seems uncomfortable with "*1e-6"...
I know why division by
1e6
works, and why multiplication by1e-6
does not work, and seriously, it has nothing to do with Swift "feeling comfortable" with one but not with other. What I do not understand is: what are the grounds to acceptx / 1e6
as correct andx * 1e-6
as incorrect, and what part of specification tells me thatx / 1e6
is correct and I should use it, and thatx * 1e-6
is incorrect and I should not use it.I know how numbers here work and why both solutions return slightly different results. And I know it has not much to do with comfort level of Swift. But I don't understand why
x * 1e-6
is rejected, and how descritpion explains that I must usex * 1e6
. "Hobovsky, your solution is wrong, because..." why?For what it's worth, the
Double
value of1.146651
also has more than 6 decimal places, just not "clearly". The idea of "avoid discussions about rounding by truncating to 6 decimal places" causes problems instead of helping, is unfortunately based on false premises, and on misunderstanding of how numbers work on fundamental level. If you can explain whyx / 1e6
is acceptable andx * 1e-6
is not acceptable, feel free to resolve this issue."feeling comfortable" was a miserable attempt to be fun:-(
I don't know why x / 1e6 is "correct" but I know that x * 1e-6 is not: "1.1466509999999999" doesn't seem to have 6 decimal places.
You couldn't seriously imagine that I had reached your level:-)
I'll let that issue for what it's worth.
I suggest to spoil the expected rounding method as comments in the solution setup (at least for Swift).
Maybe though "floor(res * p) / p;" seems "usual" and common to many languages. Let's wait for the oracle's opinion.
This is exactly the key to understanding the problem.
1.1466509999999999
does not seem to have 6 decimal places, right. But1.146651
, even though it seems to have 6 decimal places... also does not have 6 decimal places! That's why the statement in the description to "truncate to 6 decimal places" is the clu of the problem: if you expect your answers to beDouble
, it is not possible to truncate1.146651
to 6 decimal places, even if it might sometimes look like this.Just to make exactly clear what I am arguing about: my main point is not that
x/1e6
is wrong and should not be used, it can be used if it is described properly in requirements. My point is that "truncate/round to 6 decimal places" andx/1e6
are not the same. Description does not explain exactly what users should do, and the thing which users have to do to pass is not accurately described.It's OK to stick to
x/1e6
if it is unambigously and clearly described in requirements. "truncate to 6 decimal places" is not it - this is what I argue about.There is only one correct solution: return the full-precision result (no rounding, truncating, flooring, ...) and compare with an absolute tolerance of 1e-6. The truncated value should be within the tolerance, so no backward compatibility issues.
All other workarounds, sooner o later, will fail.
I agree with mauro-1. Approximate equality should be used in every language, with no rounding whatsoever. I removed the note about rounding from the description, and fixed several languages. A specific issue should be opened for the remainder.
Edit: opened here
[Swift] when (n > 170) the output is allways "nan" so kata cannot be complited in this language
This kata is difficult to be completed in Swift because of how it handles rounding, but the fact that
n
goes over 170 is not a problem.I passed the test and all test options,but i'm failing at that it is saying NaN for big numbers(bigger than 180).Could anybody help me how to avoid this,please?
Sorry, asking for help is not a kata issue. You can read: https://docs.codewars.com/training/troubleshooting.
My attempt keeps getting timed out, even though it is saying that i passed all of the test cases. I've been optimising my code and ive narrowed the function down to one line of code, still getting the same issue. (python)
Timing out is not a kata issue.
D translation
approved some time ago.
NASM translation
Approved.
This comment has been hidden.
I tried several solutions. The tests are fine when the code is fine.
Later I realized what was going on. Such a large number was simply out of reach.
it seems like JS doesn't know how to handle such big/small numbers. When the number approaches 200, NaN or Infinity starts to be output :
{ number: 200, result: NaN }, { number: 22796, result: NaN }, { number: 1011, result: NaN }, { number: 10110, result: NaN }, { number: 188, result: NaN }, { number: 523, result: NaN }, { number: 19182, result: NaN }, { number: 10481, result: NaN }, { number: 193, result: NaN }, { number: 180, result: NaN }, { number: 185, result: NaN }, { number: 175, result: NaN }, { number: 46541, result: NaN }, { number: 185, result: NaN }, { number: 45941, result: NaN }
yeah, same here, how is it possible? can even be completed this kata?
(see here)
done + used approximate equality instead of rounding + strict equality
Cool kata, but after 5 hours I have a problems with stack Exception in thread "main" java.lang.StackOverflowError
Still thinking how to work with n>6000!
I spent 3 hours and Execution Timed Out (16000 ms) in Random Tests (((
My code is giving the expected results but its always faild with exit code: 1. This is my output screen:
Test Results: going_Tests Fixed__Tests Expected: equal to 1.2125 Actual: 1.2125
For some reason that I don't know an error appeared when the kata was automatically updated. "TESTS" fixed. Unfortunately your code fails on "ATTEMPT". Thanks for your post.
Ruby kata tests numbers higher than 10000
Javascript kata tests random numbers, no higher than 200
Should have similar attempt tests between languages
Where do you see that? All languages don't have the same facilities or speed. Nevertheless I changed the JS tests.
Not as a strict rule, but it makes sense for the complexity to be similar at least
Javascript was just way easier, needing less optimizations
I've run the exact same code in JS and Ruby
JS took 900ms for all tests to pass (only very low numbers were tested), while the code in ruby exceeded max time and broke at numbers higher than 10.000
A good reason to better your Ruby code:-)
I want to use Map<number, number> for memoization in typescript but it is not supported in version 2.4. Why can't I use version 3.* to solve this Kata?
My execution time : 5982 ms Top Solution execution time : 582 ms
want to kill myself.. ! :(
I'm trying to use BigInt object in JS, but getting errror that is not defined. The object is built-in feature. Please advise
BigInt is not available in the NodeJS version used in this kata (v8.13, BigInt is available from v10.4). You can't use it.
ISSUE
This problem has several issues, such as compiling huge numbers in Python 3.8
I passed 8 test cases with NO remaining cases, yet I was met with an error: 'int too large to convert to float'.
These problems should not be designed this way.
This kata has been solved more than 800 times in Python. Your need to find another approach, and this is not a kata issue (an issue is a bug in the kata, this kata has no bugs). Please read this: https://docs.codewars.com/training/troubleshooting/
Overflow error i tried a diffrent apporoach to the challenge still same problem
An issue is a bug in the kata, not your code not working. Please read this: https://docs.codewars.com/training/troubleshooting/
This comment has been hidden.
This is a useless message. Concrete issues have already been raised, hopefully they get fixed someday. See there: https://docs.codewars.com/training/troubleshooting#post-discourse
Node 12 should be enabled (Refer this and this for more info)
Python new test framework should be used (Refer this & this for more detail)
Ruby 3.0 should be enabled (Refer this & this for more detail)
Typescript 3.3 or above should be enabled, refer this for more info
.
This comment has been hidden.
Nice Kata!
This comment has been hidden.
I answered your question in a previous post. You said "could be a problem with truncating my solution with std::round...". Because you used "round" I asked if you read the description: the description asks for "truncating", not for "rounding". 3716 people passed the kata, 401 with C++ so it is perfectly doable and your problem doesn't come from that.
In fact I looked at your solution and your problem comes from calculating "factorial n" which gives you lots of floating errors. That is not the good way to pass the kata. I won't say more since I want that users can pass the kata but without giving them the solution.
BTW it's not useful to put lots of issues (the problem is not in the kata but in your code) or to downvote my answers (I can do the same...).
Well your approach to aswering is really rude. Instead of helping you just write "Did you read the description?" and after that, you brag about how many people passed the test. It's not my duty to calculate everything exactly like you did. I don't think that's the way katas should suppose to work.
This has no point
But that's YOUR problem (as you say), so the kata isn't broken. Label ISSUE is used for things like broken tests or incorrect description, etc. If it is one of those, then you should provide more information about it.
To be on the safe side, you should be using 'question' label.
The author is hinting you that your approach is incorrect (he's the only one who can see your current solution AFAIK)
:D no. I believe he's showing you these numbers to prove that kata works as intended and many others didn't experience such problems.
BTW, if you want real-time help from others, you should try using CW discord channel or gitter (check 'forum' section on the left)
"Expected: equal to 1.275 Actual: 1.275"
Did you read the description?
Truncating is not rounding. I don't see an issue there, your code doesn't follow the description. Note that 401 people passed the C++ kata.
What do you mean? Do you even understand my question? Could you please at least tell me how to truncate in c++. What i understand there is no clear way to just cut off the number at a decimal point.
I actually wrote it wrong here i dont do round() I did trunc() or floor()
I got :
Expected: equal to 1.275 Actual: 1.275
_(--)/
Did you read all of the description?
This comment has been hidden.
OP left the building
There are no primitives for big floating numbers in javascript. If so, why offer that language?
Because 476 people passed the JS kata without bigfloat.
Good enough.Back to thinking then.
This comment has been hidden.
Asking for help is not an issue. PS: did you read all the description?
Sorry for marking it an issue. My mistake. I reread all the description and it says to truncate my answer to 6 decimal places. I've tried using '%.6f'% and importing Decimal and all sorts of things to get the last digit to match your tests, but no matter what I do some of my answers are off by 0.000001.
I know you're probably busy with more important things, but I would love if you could help me.
Note, your kata's are wonderful and it feels so satisfying when I complete one correctly.
You can google "Python truncate to decimal places". I think the easy way to truncate is to take the
int
of "...". I am sure you will find what to put instead of "...".Thanks so much for the reply. I got it to work. The fact that someone like you would respond so quickly to someone so new at coding is why I love this community.
This comment has been hidden.
This cannot be solved in PHP, as the tests are flawed:
"Failed asserting that 1.146652 matches expected 1.1466510000000001."
Sorry, not a kata issue. Did you read the entire description?
@g964: Please note the error message I posted: I am providing the rounded number asrequired, while the expected number is unrounded.
same problem
same problem
Failed asserting that 1.146652 matches expected 1.1466510000000001. Failed asserting that 1.0067120000000001 matches expected 1.0067109999999999.
Notice that the test (you can read it in "Sample Tests") is
$this->assertEquals(1.146651, going(8));
so the expected is1.146651
but PHP "assertEquals" shows it as1.1466510000000001
.Hello,
I'm working in R and running into issues regarding large values (specifically going from 170 to 171). Is the remark at the bottom of the description an indication that we will need to install a package to handle large inputs? Or is there a way to work around the 171 problem in base R? Note: I am only wanting a "Yes, there is a way to work around the 171 problem in base R" or "No, there is not a way to work around the 171 problem in base R." I have never tried installing packages in CodeWars and therefore have no idea if it is even a thing or not.
"Yes, there is a way to work around the 171 problem in base R" because there is nothing peculiar with 171 but maybe you must change your approach to the problem. "Is the remark at the bottom of the description an indication that we will need to install a package to handle large inputs?"" No, only to take the good way. You can't install packages at CW.
Okay, thanks.
I ran my code a couple time - I am passing all the tests, but I am also getting an exit code. Am I doing something wrong? I tried adding import sys sys.setrecursionlimit(10**6) into my code, but then it doesn't run at all on here - runs fine on my computer
Solve in Ruby, use bigDecimal Fail in 62 Test-case for n ~ 48_000 It needs more than 12 seconds for work.
You don't need "bigdecimal".
whithout 'bigdecimal' I have NaN when n > 170 will try
I have tried to calculate all terms in path from 1 to n like (1! + 2! + ... n!) and then divide it to n!
Calculating all factorials will not work, factorials are too large and take too long to compute. bigdecimal is not really necessary, problem is perfectly solvable with floating point numbers.
You need to think of some better approach than calculating all factorials. Work with the formula with pen and paper, you might find a way to reduce some terms in some way.
I'v already done it better.
This comment has been hidden.
if n > 170, then it return NaN, using JS, with others numbers it works
same for me.With JS it is not going well.
Can anyone confirm this is solvable in JS?
Please look at the top of the page: 387 people solved the JS kata.
Hi, racket version is initialized with
(require going)
, should be(provide going)
, otherwise the tests don't work.Modified, thanks!
.
The hardest part was trying to figure out when you should round or limit the number to 6 places.
In C langueage I receive statement like this "The expression (expr) - (act) <= (1e-6) && (act) - (expr) <= (1e-6) is false." and I don't understand it. Anyone know waht I do wrong? Almost every my test passed, but sometimes I had diffrent number on last digiit. Is it allowed?
This comment has been hidden.
I already use double long and the test case use 10110 which mean 10110! = 5.229e+36099 and the max capacity of double long is only 1.18973e+4932. Any suggestion?
This comment has been hidden.
This comment has been hidden.
@hobovsky Your comment is actually a little bit misleading. You need to calculate n! because it's not possible to rewrite the formula so it doesn't contain n!.
What you can do is rewrite the formula in a way you can calculate the result more efficiently but you always have to calculate n!
This comment has been hidden.
EDIT: C++ version of the tests was fixed, assertion messages are better and there are no more strict comparisons.
~ Test suite in C++ version is screwed because a) assertion messages truncate results a few digits shorter than actual requirement, so you cannot see what you did wrong, and b) it uses strict comparison in assertions, what is incorrect even for truncated values, because it depends on the way how you truncate/round/order of operations/many other factors. To have your C++ solution accepted, you either have to perform calculations in almost exactly the same way original solution does, or refer to some tricks like round via string representation with precision of 7 digits and hope it gets expected double value. Or just skip C++ version and go straight to C, because there tests use proper(ish) tolerance comparisons. ~
When I first wrote this kata (3 years ago) I wanted to put in evidence some rules when calculating with doubles:
Maybe I was wrong about these aims... nobody is perfect! I knew there would be discussions about the tests with no tolerance so I have limited to 6 the number of decimals of the truncated result; the variety of solutions through all languages seems to show that with 6 decimals there is no need to do the calculations in the same way original solution does nor to use tricks. Nevertheless in some more recent translations I introduced a tolerance with a custom "assertFuzzyEqual" test function. I think C++ tests are not "screwed" (though maybe more difficult than in the C version) since several guys passed with different kinds of code. Sorry for this long advocacy. PS: @hobovsky -> thanks for your dedication to CW!
About kata/tests:
Default assertion messages seem to display values with 6 digits of precision, while kata requires 7. That's why I (and not only me, as it seems) get really useless message of
Expected: equal to 1.14665, Actual: 1.14665
while values are Expected: 1.1466510000000001, Actual: 1.1466509999999999. It would be really helpful if tests provided customized (instead of default) assertion messages with better precision of actual/expected.Truncation is really not helpful, because value like
1.146651
expected by one of the test... simply does not exist. It cannot be represented by double value, and it can be either1.1466510000000001
or1.1466509999999999
, but there is no such value as1.146651
, no matter how much you'd like to truncate it. Even if you dodouble foo=1.146651;
,foo
is not equal to1.146651
, but1.1466510000000001
.Ad "[...] the variety of solutions through all languages seems to show that with 6 decimals there is no need to do the calculations in the same way original solution does nor to use tricks" - would you be so kind then to take a look at my solution and tell me what exactly I do wrong that my result misses the expected value?
But as you say, you created the kata long time ago, and you probably know all of this now. Problem is that you've probably long forgotten about the issues, but new users still encounter them, and get frustrated. I really mean no offense, I really do not mean to attack you or anything, but all I want to do is to warn potential users who would want to solve the kata, and leave some remark for those who would like to author a kata so they could see what to avoid. I do not mean to bash you, nor to bash the kata - just trying to leave some info others could find useful. I did not even expect any particular feedback, and honestly I even thought that if I would get any, it would be rather something like "GTFO", or similar ;)
And your dedication and contribution to CW is much bigger than mine. Really appreciated.
Regards!
I modified the testing function in C++. I hope you will have a look to see if it is correct. Thanks for your help and your kind posts!
Yay, so much better now! Thanks! But example tests seem to be not updated :)
Changing my vote right away!
Sorry, I only changed the "SUBMIT" tests...
Getting error - java.lang.NumberFormatException: For input string: "�"
Hi, I'm using Swift and I get a "exit code 132" when I run the attempt. No problem at all with the running the sample tests. There is no information provided on what is causing the issue. Any ideas?
the factorial is overflowing at some point. Try using 100, 200 and 1000. They're using numbers this large in their test cases
This comment has been hidden.
In php
$res = substr($res,0,strrpos($res,'.')+7);
is giving NAN, but,
$res = substr($res,0,strrpos($res,'.')+6);
is giving correct result without last number.
When I was testing it on my server it was working without problems.
PS. Only 7 isn't working
Not an issue.
I'm using GO 1.11
I found an issues in my solution when i run locally
even after got the Best Practices solution the same issues still exist.
For which values of n do you got that? If you get
-9.223372036854775e+12
for a given n, your code is clearly false... I tried a few solutions (including Best Pratices ones) and saw no problem. You can see at the top of the page that 46 (out of a total of 1973) guys passed the Go kata. If there had been problems don't you think that somebody would have already seen them? ............... Since you seem new to CW here are some general guidelines about posts:Issue: problem in the kata itself (description, wrong tests, wrong internal solution...)
Suggestions: well, that part is clear
Question anything else that is related to you having a problem solving a kata
For information, when you post issues:
provide ALL the useful information:
check, DOUBLE check that this IS an issue, meaning that the problem is in the kata itself and not in your code. If it's in your code, post rather a question If you pass this step, you still have to prove/explain what the issue is (and if you can provide fixes, it's even better)
thanks @g964 for your reply, I reviewed my code again and it was my fault.
I think there is a mistake with the examples. going(8) => 1.146652, but in the example is 1.146651.
I use Ruby
Did you read the description?
going(8) -> 1.1466517857142857
which truncated gives1.146651
.1.052787 should equal 1.052786 ??? 1.052787 is the output and I'm not even rounding it.
When you post, 1) please say which language, 2) post between 3 backticks what the console said; otherwise it is difficult to answer 3) better to post a question than an issue. I suppose it is Python. I tried a few solutions and had no problem. Look at the top of the page: 359 guys passed the Python kata; we can think that if there were errors, we would have seen them, no? Cheers.
Maybe the question is worded poorly. Which number wins? What does that mean? The formula given produces one result. I'm failing one test because it looks like it's supposed to be rounded down? Is the questin asking if the number headed towards -inifity will reach bufferflow before the number heading to infinity?
How to handle these ?
1.146652 should equal 1.146651 1.052787 should equal 1.052786
This comment has been hidden.
thanks
I love it when a plan comes together - in the search for accuracy a whole different formula emerges :o)
This comment has been hidden.
From what I can tell, the
Is it going to 0 or to infinity?
part is fundamentally wrong as:Everybody knows that, it was simply a way to introduce the kata without giving the answer...
i think what he meant was, if u try to calculate 1/n! and the sum seperatly u will face two problems one them is 1/n! converges to 0 making ur entire result =0 and the sum overflows so it goes to infinity the statement was probably a hint to this problem and that you should try to find a way to avoid both of these problems and a simple way to do that is to change the formula, it actually helped me find the solution to it.
I need some help. Solving it using R. I have resolved the accuracy issue but getting NaN(Not a Number) output for a few cases. Seems like i am missing a few test cases. Can someone please suggest how to overcome this problem?
This comment has been hidden.
The test uses equal comparations on floating points (this is bad, very bad practise!). We have to round it to 6 digits using floor(). This is still bad, because the results could be in the form 1.24499999999564, while answer is 1.245. The numbers are close enought, but by comparing truncated number we get wrong answer. If no one want to repair this one, just remember to compare floating points in proper way next time:)
This comment has been hidden.
Not an issue. It's a problem of your own code.
You don't want to make your subsequent result bigger and bigger. Maybe in the other direction :)
Hi, Im having a problem with the solution in C.
Using a
double
will get me stuck on test 8 where it will reach Infinity and NaN.I got around that by working with
long double
and casting the end result to adouble
.But that gets me stuck o the test where
as it will result in the following:
I fixed it with an ugly hack where i return the expected result if the result is
NaN
.I tried some googling to find out what data type i could use, but no succes yet.
I would love to know how i can solve the kata correctly. I really like this one
This comment has been hidden.
In the same boat as you. I have tried using the numeric limits library, but I only get close 0.999999. I am not sure I know what to do with inf in c++, long double is as about as large a data type as I know, without using the GMP library. I would like to understand what should be done with calculations that reach beyond the limits of standard data types as well.
This comment has been hidden.
Thanks!
Great Kata. Thank you!
Thanks!
This comment has been hidden.
Could be a CW problem. It happens sometimes when servers are too busy.
This comment has been hidden.
I dont know why but it seems PHP rounds numbers (by function round()) the different way then the tests expects or maybe it depends by OS or CPU registers. But if we do round by "low-level-coding" (without predefined standart functions then it works fine).
Yep, something is wrong here:
But I don't know what you mean by:
This comment has been hidden.
I'm getting the same error as others in C++.
Any ideas?
Did you read the posts of @DrGre below? I think there could be a CW bug somewhere but 54 guys passed the C++ kata...
@integral: I had a similar issue (in Clojure). The problem was, that my return value was not 1.2125, but something like 1.212500000000000001234 (which still was printid out like 1.2125). So, you can try the following: printf("%f", going(n) - 1.2125), and see if you get anything else than zero.
This comment has been hidden.
Everybody knows that, it was simply a way to introduce the kata without giving the answer...
This comment has been hidden.
I think there is a problem with the C++ testing. I got the following: Fixed__Tests ✘ Expected: equal to 1.17321 Actual: 1.17321
Random_tests ✘ Expected: equal to 1.05574 Actual: 1.05574
Maybe you should report that as bug of the C++ CW platform: Forum -> Bugs.
The bug report site said "If you have found a content related issue with one of the kata, please file the issue within the discussion section of that kata. To do this, you can create a comment and set its label to be an Issue. "
I just tried a few different solutions and they worked fine. 36 guys passed the C++ kata. Maybe you could try once more. The kata tests are using the test unit framework of CW and have no problem by themselves. Look at "Example tests", you see:
The
Assert::That(ans, Equals(sol));
part is done by the testing framework and if it does a bad job the kata has nothing to do with that. Please fill the issue at CW: evidently all problems are kata related...Where I can see Equals(sol) source? I'm tried round, floor, ceil, trunc with 1e-6 precision (and -7 and -5) and I can't pass the first test. All tests on my desktop are passed when I compare like abs(res - expected) < 1e-6. Or which function did you use for truncating? std::floor(res * 1e6) / 1e6 - didn't work. (round, trunc, ceil) Don't understand, how some people passed this.
going_Tests Fixed__Tests Log 1.275 1.2125 1.173214 1.146651 ✘ Expected: equal to 1.14665 Actual: 1.14665
Random_tests Log ****************** Random Tests **** going 1.071828 1.055739 1.077427 1.038521 1.052786 1.173214 1.032292 1.101158 ✘ Expected: equal to 1.10116 Actual: 1.10116 I think this is some issues in Equals function
I don't know where you can find the Equal(sol) source:-( I can only repeat what I said above. I tried some solutions and they worked. Maybe you could post your code (marking it as spoiler) and if I had enough time I will try it.
try to wrap your return into
return round( re * 1000000.0 ) / 1000000.0;
Hi all,
Trying to implement a solution using Java. But I can't achieve a requested performance level :( Tried to use BigInteger and BigDecimal to deal with factorials of big numbers but in this case I get a timeout error after 3 or 4 successful tests.
Could you please drop a hint which the algorithm should I use?
Hint: Simplify the equation first, don't try to calculate the two terms separately.
Thanks for tip, @PMV.
In description: "Are these number going to 0 because of 1/n! or to infinity due to the sum of factorials?"
But un = (1 / n!) * (1! + 2! + 3! + ... + n!) are always greater than 1 and never going to 0! Or I do not understand something?
This comment has been hidden.
I think
std::floor(result * 1000000) / 1000000;
should work fine. You might want to look at the result before truncating, because 1146652 is rouned up.keep getting these kind of errors
Fixed__Tests
✘ Expected: equal to 1.14665 Actual: 1.14665
Random_tests
****************** Random Tests **** going
✘ Expected: equal to 1.04007 Actual: 1.04007
Just ignore these unit tests and submit? (They use
AreEqual
which is not right for floating point numbers comparision.)There seems to be a problem with C++ tests. My solution fails even though it returns the correct result, eg.
Fixed__Tests
✘ Expected: equal to 1.275 Actual: 1.275
The problem I believe is in the floating point comparison, if I replace the line
with
then the local tests pass.
Yes I could change the tests but other guys (not only I:-) passed the kata such it is. Did you truncate to 6 decimal places? Furthermore
1.275
is1.275
... I don't understand that. Did you output your result ? Can you pass the other tests?Looks like it was a silly mistake of mine, I was using floorf which returns a float and only caught that mistake when I tried to print the binary value of the result! Sorry for that, marked it resolved.
Clojure naive solution with memorize falls with StackOverflowError in Clojure 1.6, but work in 1.8.
Please check tests in the C# solution. I always receive "unknown error".
Compilation succeeded - 1 warning(s)
{"stdout":"","stderr":"/tmp/csharp116421-20-skhjib/fixture.cs(12,8):
warning CS0414: The private field `SuiteTests.randomGenerator' is assigned but its value is never used\n","wallTime":0} Unknown error
CW has changed the C# version. Before that there was no warning... I fixed it but I fear that you have a problem in your code since the compilation succeeded. Please keep me informed.
My code can't pass tests 9-11, but now I see test results, it was only "Unknown error" before. Thanks for quick response.
This message keeps emerging. Process was terminated. It took longer than 6000ms to complete
Try to optimize your code then. It may either take too much to process, or you're getting into a loop.
Hi. I got an error for n = 10110, "Process was terminated. It took longer than 10000ms to complete". What can I do?
Improve the solution for better performance.
Can someone provide the input value for test10 and test11? I'm getting errors in these testcases and cannot figure out why.
You could print the input.
Can't believe I didn't think of that :). Thanks!
I still have the rounding issue with Python. round(result, 6) doesn't help either as the last digit may differ from what is expected. Right now I have to use a rather ugly math.floor(result*1e6)/1e6 statement. Would this be possible to fix? Thanks!
Too late to change that, it will invalidate more than 430 solutions. The description is clear: "going(n) will return "result" truncated to 6 decimal places"; truncating is not rounding and I don't find
math.floor(result*1e6)/1e6
ugly:-)OK, I guess it is only that the sentence you quote is ambigious. It can be interpreted as the rounding/truncating is taken care of by the framework. In any case, I really like the katas you post, thanks for them!
Thanks for your post!
Hi! I also noticed the rounding issue.
The task asks for 1.2125, but that is a repeating fraction that can't be represented exactly in binary (like 1/3 is .333 etc in decimal), so once put in a double it is around 1.2124999999999999. When the program correctly truncates that to 1.212499 it fails the test case.
In general rounding won't work math wise for comparing floats, because it will tolerate a varying amount of error that might be infinitely small. For example if you are truncating .9999999999 to 0, with only .0000000001 error it will truncate differently to 1. But for .5 you can have a whole .5 of error before it will change the truncation.
Luckily this is really easy to fix, the testing framework already accounts for this and you can just add a third parameter to Assert.AreEqual(expected, actual, tolerance) which is the tolerance amount. If you make this value large enough, say .0000015, it should work with all the existing solutions too.
Thanks!
Are you talking about C#? I don't see from MSDN that Assert.AreEqual accepts tolerance as a parameter but I could be wrong... Unfortunately there was no guide for that at CW and there is not one, even now. I wrote this kata rather long time ago. I used the DELTA parameter in Java for this kata and now for this kind of kata I'm using a kind of assertFuzzyEqual in all languages. Nevertheless lots of guys passed the kata (373) which proves that it is doable:-) BTW I don't see very well how you truncate ".9999999999 to 0, with only .0000000001 error". Furthermore I didn't ask for rounding but for truncating. The problem doesn't come from truncating it comes from the way languages work with floating numbers and from the order in wich operations are done. Give me some reference for Assert.AreEqual with a tolerance parameter and I will try to modify it when I have time but I am afraid that tolerance doesn't exist in the other languages. Thanks for your feedback.
Yes, for C#, I noticed that that the test case used an open source framework called NUnit. I tested it just now with the example test case, and if you change the first one to Assert.AreEqual(1.275, Suite.going(5), .01), it sets the tolerance to .01. It's a common task so I'd hope other frameworks build it in but I don't know if you can just add another parameter in Haskell :)
For the example say for test case 1 the expected math result is .9999999999. And the truncation rule is 0 decimal places, so .9999999999 will get truncated to 0. Then a user solution is .0000000001 too high because of floating point precision, and it comes out .9999999999 + .0000000001 (due to floating point error) == 1.0000000000 Now when the 1.0000000000 gets truncated it will be 1, which does not match the expected result of 0. So even though the solution was only .0000000001 too high, it fails the test case.
Using the same rounding, say for test case 2 the expected math result is .5000000000, truncated to 0 places that would be 0. Say the user does the math wrong and they get 0.0000000000. Truncated that is also 0. So that test case passes. Using the same rules, for this test case a solution .5 off can pass, while for test case 1 a solution .0000000001 off will fail.
It works the same whether the numbers are .000999999 with a .000000001 positive error making it go up to .001000000, then being truncated to 3 decimal places to .001 or .000, everything is just moved over a few decimal points. Something similar is happening in one of the test cases for this problem.
So rounding or truncating seems like a good idea at first and the obvious way to do things, but the problem is for numbers close to the rounding / truncating point even a small precision error will change the result (and numbers far away from the rounding point will have 100x more leeway). It's just super unlucky that one of the test cases in this problem has a number that ends in 9999999999 (when stored in a double).
BTW the reason why I grouped rounding / truncating is they are pretty similar in how they work, it's easy if you look at it on a graph! (hopefully the link goes through)
http://www.meta-calculator.com/online/xg82tkvrqybi
I used the floor() function like you use in your solution, the other line one is round().
It seems that the problem is only with C#. ASAP I will try with a tolerance of
0.000002
in C#. What do you think of that?That should work! I just tested it, it looks like if you put a constructor in your test class public SuiteTests() { GlobalSettings.DefaultFloatingPointTolerance = .000002; } it will use it everywhere, that way you don't have to change any tests.
I made the change, thanks for the tip! Could you give me a good link to the NUnit Framework?
It looked like the version for codewars is 2.6 (https://github.com/Codewars/NUnit-codewars) and the docs I was looking at were http://www.nunit.org/index.php?p=equalityAsserts&r=2.6
I'm not an expert in it though I've just been using a few assert functions like AreEqual
Thanks for the link!
This comment has been hidden.
Please which language? C#? In fact the console writes
Expected: 1.2124999999999999d
whereas the test asks for1.2125
and you have1.212499d
. Certainly we don't make the calculations in the same order. It's always the problem withdouble
. See the second exemple in the description and you will see what in fact I get.Looks OKish for me. In double (any language) 1.2124999999999999 == 1.2125 which probably is what is expected, so no error here. The only problem is in formatting the expected value when printing, it might be worth fixing.
Lot of thanks for your participation! The problem with "assertAreEqual" is that I have no power on the printing. I should have written a fuzzy assertAreEqual... unless that exists in NUnit Framework.
I am testing it in C#. And see that there is exactly case in comparison. When I am truncating the number I have a signle issue as I wrote above when I am skipping the truncation I see the follwing Test01 Expected: 1.2749999999999999d But was: 1.2749999999999995d at SuiteTests.Test01 () [0x00000] in :0 Test02 Expected: 1.2124999999999999d But was: 1.2125000000000006d at SuiteTests.Test02 () [0x00000] in :0 Test03 Expected: 1.173214d But was: 1.1732142857142847d at SuiteTests.Test03 () [0x00000] in :0
It is really matter of asserting the final values. Can you change your Assert.Equal to to Assert.isTrue(Math.Abs(expected-actual) <= epsilon), where epsilon is 0.000001?
This comment has been hidden.
May be interesting in terms of code writing to address the large numbers, but mathematically it is just boringly trivial :(
This comment has been hidden.
Which language please? Could you post between 3 backticks what the test returns? Until now nobody complained about that:-)
C#
All tests return results truncated to 6 decimal places.
"Keep in mind that factorials grow rather rapidly, and you may need to handle large inputs."?
From the perspective of mathematical analysis it's very easy to tell that the series does go to 0, because 1/n! multiplied by n! equals 1, and n! is the divisor of the rest of addends :)
and for that reason it goes to 1, not to 0
Hi all. Please give me a tip, which algo did you use to div extra large numbers. In my case I used exp^(log(a) - log(b)) algorithm but this algo give me the accuracy to the fifth decimal place, but in some test cases I need accuracy to six decimal. Please help. P.S sorry for my english.
Try using Math.expm1 for JS only. Not sure about other languages.
This comment has been hidden.
Please which language?
yesterday i have done this task :) thank's
Good!
All the solutions depend on rejiggering the problem to a different form that avoids huge numbers. Implementing the equation as given doesn't work within the allotted 6000 msec (though it does work, if you use BigInteger, of course).
So this is a math problem, not a programming problem.
But I don't understand the math in this case. Can somebody explain it, or point to the article on the web where they found it? (My google-fu is not strong enough.)
Programming needs at least some maths background...
My python code works fine when I click on "Run Tests" but when I click "Submit" I get the following:
This happens over and over, but if I change the code to give an erroneous result and submit, there aren't any communication errors. I also checked status.codewars.com and everything seems to be running normal.
I wrote my own memoize and factorial functions, and my truncation function converts Decimal to float.
Does anybody have any clue what's going on? I'm relatively new to the site, and I've completed only about 20 problems so far, but this is the first time I'm encountering this error.
You should simplify the equation to be in-line with an algorithm in O(N) time complexity.
This comment has been hidden.
Don't post code! What is your problem?
So I've been bashing my head against this for a while. I've got it to work with various factorial algorithms locally (variations on recursive, variations on iterative, stirling, using a matrix constant, combinations of these and others).
For really large n! my session times out.
I'm getting to the point where I think this actually doesn't work in Ruby?
This comment has been hidden.
Please help me understand:
Expected: 1.275, instead got: 1.275000 Expected: 1.2125, instead got: 1.212500 Expected: 1.173214, instead got: 1.173214 Expected: 1.146651, instead got: 1.146652 Expected: 1.052786, instead got: 1.052787 Expected: 1.034525, instead got: 1.034525 Expected: 1.020416, instead got: 1.020417 Expected: 1.008929, instead got: 1.008929
Which language? "Expected" is the result you should have given, "got" is the result you gave. Seems that your truncation is a bit wrong. It is asked for a truncation not a rounding.
Javascript. I just don't see any difference for a few of the failed tests. I understand what you're saying about rounding vs truncation (I think I was using Number.prototype.toFixed(), which I think rounds), but for several of the tests that should be a moot point.
While I have your attention: I tried memoizing for factorial but still get NaN, which I assume means it's having a hard time with big numbers but I'm not sure what to try next. Maybe iteration...
This comment has been hidden.
This comment has been hidden.
result = +result
hello, i got this "Expected: 1.005025, instead got: NaN" ( when n >200 ) why is that?
Which language? You got "NaN" which means "Not a Number" because your algorithm was not build for having big numbers and there are lots of big numbers in the tests. Try to calculate factorial(200) with your algorithm. Maybe you will understand.
Try calculating 172! (172.fact/factorial(172)) and check its class. Should be a Bignum (you might want to require some core library which allows you to manipulate Bignums/BigDecimals...
Which language? Ruby? See my answer above.
if u got this in JS, i think u could try to use strings(or even arrays) instead of numbers
if you do it in JS ,when n>200,1!+2!+...+n!and n! are both infinity,infinity/infinity is NaN ,but I don't know how to solve it
This comment has been hidden.
Results are always truncated the same way!
Hi guys, I have a problem trying to solve this for the submission cases in Python.
For the third test case,after rounding, this is the response I get: 1.146652 should equal 1.146651
However, when I print out the float prior to rounding, I see that it is 1.14665178571, which, to my understanding, means that the answer should be 1.146652 instead of 1.146651...
Where am I going wrong??
The description says:
It's said truncated, not rounded...
I'm going to repeat myself, but those questions wouldn't have arised if you
(By the way truncating a floating point number to a certain number of decimal places doesn't make sense for large floating point numbers, e.g.
12345678912345e-5
, something you should keep in mind.)This comment has been hidden.
Thanks for pointing out truncate vs rounding, g964!
bkaes, I'm going to think about what you said...
This comment has been hidden.
In fact times needed are approximately the same for Ruby and Python... but the conditions at CW between the different languages are not always the same, depend on the loads of the servers I suppose. With a good program they both need
~200 ms
at CW.This comment has been hidden.
What do you propose?
Answer threshold (+-1 differences on sixth decimal place pass) or a method for displaying the solution for JavaScript.
Look StackOverFlow or other CW solutions, you will see how it's easy to truncate, whatever language you use, even in JS! Rounding is a bit less easy and informative.
would help to clarify the need to handle large inputs
What do you propose?
A description addition: "Keep in mind that factorials grow rather rapidly, and you need to handle large inputs".
Done, thanks.
In Python I get "OverflowError: long int too large to convert to float" when submitting the result function. May be you should keep the first value in test cases lower than 170 for python?
look at the first answer - http://stackoverflow.com/questions/16174399/overflowerror-long-int-too-large-to-convert-to-float-in-python
It's made on purpose, you should look at another method; you will have bigger numbers than 170... Here Decimal isn't the solution:-(
Truncating a result usually leads to bad results. Instead, check in your tests whether the user's result is close enough to the actual one (note: I come from computational science, and you would be quartered there if you throw away any significant digit, in case you're wondering why I don't like that).
All languages don't give the possibility to have a "precision"... and truncating is the only choice.
No. In any language you can do something like
absolute (actual - expected) / expected <= relative_error_epsilon
. That doesn't needprecision
at all.For example in JavaScript, you can use something like
This needs only division, subtraction and comparison. And you probably concur that this is available in any of the Codewars languages :).
I totally agree, I had never thought of that for testing with decimals. I'll try to use it in a future kata. Until now I most often imitated what I saw in tests of other katas. Nevertheless if it is bad practice to truncate, it seems to make no harm to those who pass the kata.
By the way, is there any means to reduce the number of tests in Haskell with Quickcheck?
If you change the test cases, it won't affect those who truncated the solution at all, since they should have a relative error of
1e-6
(hopefully).Err, yes, but why would you need this? Futhermore, why do you currently generated three values instead of a single one?
I would like to reduce the number of tests because in a program I'm writing the tests take more than 6000 ms. I cannot reduce the size of the numbers because if I do that the results will often be "empty". I generated three values because I saw that the tests reproduced too often the same numbers, which is of little use.
That sounds like a bug. Did you use
property $ forAll (choose (..., ...))
?Use
modifyMaxSuccess
fromTest.Hspec.QuickCheck
:By the way, I didn't knew about that function 10 minutes ago :D.
Test.Hspec.QuickCheck
also containsprop
if you don't want to writeit "..." $ property $ ...
.Not in this case. I used
import Test.Hspec.QuickCheck is different from : import Test.Hspec + import Test.QuickCheck?
Yup.
Test.Hspec
exportshspec
,describe
,it
and theshould...
combinators. It also re-exportsproperty
fromTest.QuickCheck
.Test.QuickCheck
exports theforAll
and theGen
combinators, likeforAll
,choose
and so on.Test.Hspec.QuickCheck
exports modifiers that can be used to change theQuickCheck
settings. You could also usehspecWith
and prepare aConfig
object, but that's a little bit more cumbersome.By the way, you can simply check all those modules and functions with https://www.haskell.org/hoogle/ or http://hayoo.fh-wedel.de/.
modifyMaxSuccess works great! Thank once more.
raised here as an issue
You just published your solution in your example Haskell test cases. And while I appreciate the effort, you don't need to provide all languages at once. This doesn't give you more honor, but can lead to sub-par tests if you're not proficient in all those languages.
I published yesterday or the day before. I'm correcting a few things. Is that the issue? Edit: I re-published with the corrections about which we spoke.
Edit2: Oh! Yes! Now I understand!!! Corrected with suppression of the "solution". I wondered how happened that you had exactly the solution I gave. It made me think I was becoming better since I had the same as yours!!!
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.