Lua string.format ("%d") fails for some integers - lua

I am using lua 5.3.2 and the following piece of code gives me an error:
string.format("%d", 1.16 * 100)
whereas the following line works fine
string.format("%d", 1.25 * 100)
This is probably related to this question but the failure depends on the floating point value. Given that, in my case, a local variable (v) holds the float value, and is generated by an expresson that produces a value between 0 and 2 rounded to 2 decimal places.
How can I modify the code to ensure this doesn't fail for any possible value of v ?

You can use math.floor to convert to integer and add +0.5 if you need to round it: math.floor(1.16 * 100 + 0.5). Alternatively, "%.0f" should have the desired effect as well.

Related

Issue in Math functions for Lua

We had given task as
Read an angle in degrees, and print the tan, cosec, sec, and cot values of that angle in the same order. To use via the rad() function, convert the angle from degrees to radians for the standard library functions.
For which we written code as
x = io.read()
radianVal = math.rad (x)
io.write(string.format("%.1f ", math.tan(radianVal)),"\n")
io.write(string.format("%.1f ", math.cosh(radianVal)),"\n")
io.write(string.format("%.1f ", math.sinh(radianVal)),"\n")
io.write(string.format("%.1f ", math.cos(radianVal)),"\n")
But output is not as expect, not sure where we went wrong
Run as Custom Input
30
Your Output (stdout)
0.6
1.1
0.5
0.9
Expected Output
0.57735026918963
2.0
1.1547005383793
1.7320508075689
Correct code which is working perfectly is
x = io.read()
function cot(radAngle)
return 1 / math.tan(radAngle)
end
function cosec(radAngle)
return 1 / math.sin(radAngle)
end
function sec(radAngle)
return 1 / math.cos(radAngle)
end
local radAngle = math.rad(x)
print(math.tan(radAngle))
print(cosec(math.rad(x)))
print(sec(math.rad(x)))
print(cot(math.rad(x)))
How can you expect to get the correct result if you calculate cosh(x) instead of csc(x)? You're using the hyperbolic cosine to calcuate the cosecant. I think it is obvious why your results are not accepted.
You use sinh(x) to calculate sec(x) and cos(x) to calculate cot(x).
You're confusing mathematical functions. That's not a Lua programming problem.
I suggest you spend a few hours on researching trigonometric functions.
https://en.wikipedia.org/wiki/Trigonometric_functions
Such values are calcuated using the correct formula or function. Not by using any function of the math library that has a similar name.
cosh is deprecated since Lua 5.3 btw.
You can use math.tan to calculate the tangens of your angle.
For secant, cosecant and cotangens you'll have to implement your own functions.
Also note that the number of decimals might cause issue in result validation. Make sure it is ok to round to 1 decimal.
Example:
There is no function to calculate the cotangent of an angle. So we define one.
function cot(radAngle)
return 1 / math.tan(radAngle)
end
local radAngle = math.rad(30)
print("tan(30°):", math.tan(radAngle))
print("cot(30°):", cot(math.rad(30)))
->
tan(30°): 0.57735026918963
cot(30°): 1.7320508075689

Bad argument to 'random'

This is my code
while true do
script.Parent.Position = Vector3.new((math.random(-41.994,15.471)),0.5,(math.random(129.514,69.442)))
script.Parent.Color = Color3.new(math.random(0,255), math.random(0,255), math.random(0,255))
wait(1)
end
The programming language I am using is Lua
When I try to use this code I am presented with this error:
"15:50:47.926 - Workspace.rock outer walls.Model.Rocks.Part0.Script:2: bad argument #2 to 'random' (interval is empty)"
The purpose of the code is to randomly teleport the part the script is in around but not to far away and at the same y axis.
Can somebody please give me some form of explanation
Ps. A while ago I made a rude post on this website because I was confused at how to do a lot of things and now I understand some stuff better so I would like to apologize for my idiocy ~Zeeen
In Lua, math.random can be called 3 ways:
with no arguments
with 1 integer argument
with 2 integer arguments
It does not accept values like -41.994 or 15.471 this is why you're getting the error.
If your change your values to -41 or 15 you shouldn't see an error any more.
Lua 5.3 reference manual: http://www.lua.org/manual/5.3/manual.html#pdf-math.random
math.random ([m [, n]])
When called without arguments, returns a pseudo-random float with uniform distribution in the range [0,1). When called with two integers m and n, math.random returns a pseudo-random integer with uniform distribution in the range [m, n]. (The value n-m cannot be negative and must fit in a Lua integer.) The call math.random(n) is equivalent to math.random(1,n).
This function is an interface to the underling pseudo-random generator function provided by C.
As Nifim's answer correctly points out, there are three ways to call math.random in Lua.
With no arguments, it returns a real number in the range 0.0 to 1.0.
With one or two integer arguments, it returns an integer.
None of these directly give you want you want, which I presume is a random real number in a specified range.
To do that, you'll need to call math.random with no arguments and then adjust the result.
For example, if you wanted a random number between 5.0 and 10.0, you could use
math.random() * 5.0 + 5.0
Consider writing your own wrapper function that takes two floating-point arguments and calls math.random.
function random_real(x, y)
return x + math.random() * (y-x)
end

How to Round to the Nearest Tenth?

Given any number of the sort 78.689 or 1.12 for instance, what I'm looking for is to programmatically round the number to the nearest tenth place after the decimal.
I'm trying to do this in an environment where there is a math.floor() function that rounds to the lowest whole number, and as far as I can tell from documentation there's nothing like PHP's round() function.
There's simple snippet at: http://lua-users.org/wiki/SimpleRound
function round(num, numDecimalPlaces)
local mult = 10^(numDecimalPlaces or 0)
return math.floor(num * mult + 0.5) / mult
end
It will misbehave when numDecimalPlaces is negative, but there's more examples on that page.
You can use coercion to do this...
It work just like printf... You can try to do something like in this snippet.
value = 8.9756354
print(string.format("%2.1f", value))
-- output: 9.0
Considering that this is roblox, it would just be easier to make this a global variable instead of making a single module or creating your own gloo.
_G.round = function(x, factor)
local factor = (factor) and (10 ^ factor) or 0
return math.floor((x + 0.5) * factor) / factor
end
In my case, I was simply trying to make a string representation of this number... however, I imagine this solution could prove useful to others as well.
string.sub(tostring(percent * 100), 1, 4)
so to bring it back to a numerical representation, you could simply call tonumber() on the resulting number.

How to keep an integral number float in Lua 5.3

print(2^62)
print(2^63)
print(2^64)
In Lua 5.2, all numbers are doubles. The output of the above code is:
4.6116860184274e+18
9.2233720368548e+18
1.844674407371e+19
Lua 5.3 has support for integers and does automatic conversion between integer and float representation. The same code outputs:
4611686018427387904
-9223372036854775808
0
I want to get the float result. 2.0^64 works, but what if it's not a literal:
local n = io.read("*n") --user input 2
print(n^64)
One possible solution is to divide the number by 1: (n/1)^64 because in / division , the operands are always converted to float, but I'm looking for a more elegant solution.
Tested on Lua 5.3.0 (work2).
io.read("*n") always returns a float. So no surprises there.
If you need to convert an integer to a float, add 0.0 to it.

Objective C ceil returns wrong value

NSLog(#"CEIL %f",ceil(2/3));
should return 1. However, it shows:
CEIL 0.000000
Why and how to fix that problem? I use ceil([myNSArray count]/3) and it returns 0 when array count is 2.
The same rules as C apply: 2 and 3 are ints, so 2/3 is an integer divide. Integer division truncates so 2/3 produces the integer 0. That integer 0 will then be cast to a double precision float for the call to ceil, but ceil(0) is 0.
Changing the code to:
NSLog(#"CEIL %f",ceil(2.0/3.0));
Will display the result you're expecting. Adding the decimal point causes the constants to be recognised as double precision floating point numbers (and 2.0f is how you'd type a single precision floating point number).
Maudicus' solution works because (float)2/3 casts the integer 2 to a float and C's promotion rules mean that it'll promote the denominator to floating point in order to divide a floating point number by an integer, giving a floating point result.
So, your current statement ceil([myNSArray count]/3) should be changed to either:
([myNSArray count] + 2)/3 // no floating point involved
Or:
ceil((float)[myNSArray count]/3) // arguably more explicit
2/3 evaluates to 0 unless you cast it to a float.
So, you have to be careful with your values being turned to int's before you want.
float decValue = (float) 2/3;
NSLog(#"CEIL %f",ceil(decValue));
==>
CEIL 1.000000
For you array example
float decValue = (float) [myNSArray count]/3;
NSLog(#"CEIL %f",ceil(decValue));
It probably evaluates 2 and 3 as integers (as they are, obviously), evaluates the result (which is 0), and then converts it to float or double (which is also 0.00000). The easiest way to fix it is to type either 2.0f/3, 2/3.0f, or 2.0f/3.0f, (or without "f" if you wish, whatever you like more ;) ).
Hope it helps

Resources